# C Programming Code Examples

## C > Arrays and Matrices Code Examples

### C program to right rotate an array

``` C program to right rotate an array Write a C program to right rotate an array by n position. How to right rotate an array n times in C programming. Logic to rotate an array to right by n position in C program. 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 j=1 to n do rotateArrayByOne(arr) End for End rotateArrayByOne(arr[], SIZE) Begin: last = arr[SIZE - 1] For j = SIZE-1 to 0 do arr[j] = arr[j - 1] End for arr[0] = last End /* 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 j, N; int arr[SIZE]; printf("Enter 10 elements array: "); for(j=0; j<SIZE; j++) { scanf("%d", &arr[j]); } printf("Enter number of times to right rotate: "); scanf("%d", &N); /* Actual rotation */ N = N % SIZE; /* Print array before rotation */ printf("Array before rotationn"); printArray(arr); /* Rotate array n times */ for(j=1; j<=N; j++) { rotateByOne(arr); } /* Print array after rotation */ printf("\n\nArray after rotation\n"); printArray(arr); return 0; } void rotateByOne(int arr[]) { int j, last; /* Store last element of array */ last = arr[SIZE - 1]; for(j=SIZE-1; j>0; j--) { /* Move each array element to its right */ arr[j] = arr[j - 1]; } /* Copy last element of array to first */ arr[0] = last; } /* Print the given array */ void printArray(int arr[]) { int j; for(j=0; j<SIZE; j++) { printf("%d ", arr[j]); } } ```