I have a C++ program where I have to rotate the array clockwise according to the given number of elements to be rotated (x). For example if the input array is
[1,2,3,4,5]
given that 2 elements (denoted as x) must to rotated.
The output array should be
[3,4,5,1,2]
Code:
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--){
int n,x;
cin>>n>>x;
int a[n],b[x];
for(int i=0;i<n;i++){
cin>>a[i];
}
copy(a,a+x,b);
copy(b,b+x,a+n);
n=n+x;
for(int i=x;i<n;i++){
cout<<a[i]<<" ";
}
}
return 0;
}
What I'm doing here is that I copy the given number of elements to a new array. Later copy them back to the original array starting from 'n'. So my array will look like [1,2,3,4,5,1,2].
Later I'm printing out the array starting from the index 'x'. So that my array will look like [3,4,5,1,2].
I'm able to compile the program and I'm getting the output. But while submitting the code in a website called GeekforGeeks its complier is throwing out a Segmentation Fault (SIGSEGV).