The Program in C to right rotate an array by n elements, n given by user is given below:
#include <stdio.h>
void rightRotate(int arr[], int n, int k) {
int temp[k];
for (int i = 0; i < k; i++) {
temp[i] = arr[n-k+i];
}
for (int i = n-1; i >= k; i--) {
arr[i] = arr[i-k];
}
for (int i = 0; i < k; i++) {
arr[i] = temp[i];
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
int k;
printf("Enter the number of elements to rotate: ");
scanf("%d", &k);
rightRotate(arr, n, k);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output:
Enter the number of elements to rotate: 4
2 3 4 5 1
Pro-Tips💡
This program uses a for loop to rotate the elements of the array to the right by n positions, where n is entered by the user.
The function rightRotate() takes in the array, its size and the number of rotations to perform as its parameters.
The program first creates a temporary array temp
of size k
and copies the last k
elements of the original array into it.
Then it shifts the elements of the original array from k
position backwards.
Finally it copies the elements of temp
array to the first k position of original array.