Given a set of 'n' elements and 'r', write a generic function (Numbers and characters) to right shift the set of elements by 'r' position . If the elements are moved to the position that is greater than ‘n’ then wrap the shift process to the beginning of the collection.
For example, if the set of five elements are 1,7,8,9,12 and value of 'r' is 3 then the set of elements would be 8, 9, 12, 1, 7.
#include <iostream>
using namespace std;
// Function to print an array
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
void rotate(int arr[], int n) {
int x = arr[n - 1], i;
for (i = n - 1; i > 0; i--)
arr[i] = arr[i - 1];
arr[0] = x;
}
int main() {
const int n=5;
int r=3,i;
int arr[n]={1,7,8,9,12};
cout << "array: \n";
printArray(arr, n);
for(i=1; i<=r; i++){
rotate(arr, n);
}
cout << "Rorated array: \n";
printArray(arr, n);
cout<<endl;
return 0;
}
Comments
Leave a comment