# Circular Array Rotation Hackerrank Problem coderinme

##### Circular Array Rotation

John Watson performs an operation called a right circular rotation on an array of integers,[a0,a1,a2,…,an-1]. After performing one right circular rotation operation, the array is transformed from [a0,a1,a2,…,an-1] to [an-1,a0,a1,a2,…,an-2].

Watson performs this operation k times. To test Sherlock’s ability to identify the current element at a particular position in the rotated array, Watson asks q queries, where each query consists of a single integer,m , for which you must print the element at index in the rotated array (i.e., the value of am).

Input Format

The first line contains 3 space-separated integers, n, k, and q, respectively.
The second line contains space-separated integers, where each integer i describes array element ai (where 0<=i<=n ). Each of the q subsequent lines contains a single integer denoting m.
Output Format

For each query, print the value of the element at index m of the rotated array on a new line.

Sample Input

3 2 3
1 2 3
0
1
2
Sample Output

2
3
1

I method

``````#include <math.h>
#include <stdio.h>

int main() {
int n, k, q;
scanf("%d", &n);
scanf("%d", &k);
scanf("%d", &q);
int data[n];
for(int i=0; i<n; i++) scanf("%d", &data[i]);
k = k % n;
while(q--) {
int x;
scanf("%d", &x);
x = x - k;
if(x < 0) x = x + n;
printf("%d\n", data[x]);
}
return 0;
}
``````

II Method

```#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void cirRot(int *a, int n){
int t=a[n-1];
for(int i=n-1;i>0;i--){
a[i]=a[i-1];
}
a[0]=t;
}
void revRot(int *a, int n){
int t=a[0];
for(int i=0;i<n-1;i++){
a[i]=a[i+1];
}
a[n-1]=t;
}

int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,k,q;
cin>>n>>k>>q;
int *a=new int[n];
for(int i=0; i<n; i++)
cin>>a[i];
k=k%n;
if(k>n/2){
k=n-k;
while(k--)
revRot(a,n);
}
else{
while(k--)
cirRot(a,n);    }
while(q--){
int x;
cin>>x;
cout<<a[x]<<endl;
}

return 0;
}
```

OutPut

### hasectic

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi