Write a C program to right rotate an array by n position. Logic to rotate an array to right by n position in C program.
Example
Input
Input 10 elements in array: 1 2 3 4 5 6 7 8 9 10 Input number of times to rotate: 3
Output
Array after right rotation: 8 9 10 1 2 3 4 5 6 7
Required knowledge
Basic C programming, Loop, Array, Function
Logic to right rotate an array
Below is the step by step descriptive logic to rotate an array to right by n positions.
- Read elements in an array say arr.
- Read number of times to rotate in some variable say N.
- Right rotate the given array by 1 for N times. In real right rotation is shifting of array elements to one position right and copying last element to first.
Algorithm to right rotate an array Begin: read(arr) read(n) For i←1 to n do rotateArrayByOne(arr) End for End rotateArrayByOne(arr[], SIZE) Begin: last ← arr[SIZE - 1] For i ← SIZE-1 to 0 do arr[i] ← arr[i - 1] End for arr[0] ← last End
Program to right rotate an array
/** * C program to right rotate an array */ #include <stdio.h> #define SIZE 10 /* Size of the array */ void printArray(int arr[]); void rotateByOne(int arr[]); int main() { int i, N; int arr[SIZE]; printf("Enter 10 elements array: "); for(i=0; i<SIZE; i++) { scanf("%d", &arr[i]); } printf("Enter number of times to right rotate: "); scanf("%d", &N); /* Actual rotation */ N = N % SIZE; /* Print array before rotation */ printf("Array before rotation\n"); printArray(arr); /* Rotate array n times */ for(i=1; i<=N; i++) { rotateByOne(arr); } /* Print array after rotation */ printf("\n\nArray after rotation\n"); printArray(arr); return 0; } void rotateByOne(int arr[]) { int i, last; /* Store last element of array */ last = arr[SIZE - 1]; for(i=SIZE-1; i>0; i--) { /* Move each array element to its right */ arr[i] = arr[i - 1]; } /* Copy last element of array to first */ arr[0] = last; } /** * Print the given array */ void printArray(int arr[]) { int i; for(i=0; i<SIZE; i++) { printf("%d ", arr[i]); } }
Also read
Output
Enter 10 elements array: 1 2 3 4 5 6 7 8 9 10 Enter number of times to right rotate: 3 Array before rotation 1 2 3 4 5 6 7 8 9 10 Array after rotation 8 9 10 1 2 3 4 5 6 7
Happy coding ;)