📊📚Intermediate
Array Rotation
Rotate array elements
Array rotation shifts elements by a specified number of positions.
Program Code
array_rotation.c
C
1#include <stdio.h>23void rotateLeft(int arr[], int n, int d) {4 int temp[d];5 6 // Store first d elements7 for (int i = 0; i < d; i++) {8 temp[i] = arr[i];9 }10 11 // Shift remaining elements12 for (int i = 0; i < n - d; i++) {13 arr[i] = arr[i + d];14 }15 16 // Put stored elements at end17 for (int i = 0; i < d; i++) {18 arr[n - d + i] = temp[i];19 }20}2122void rotateRight(int arr[], int n, int d) {23 int temp[d];24 25 // Store last d elements26 for (int i = 0; i < d; i++) {27 temp[i] = arr[n - d + i];28 }29 30 // Shift elements right31 for (int i = n - 1; i >= d; i--) {32 arr[i] = arr[i - d];33 }34 35 // Put stored elements at start36 for (int i = 0; i < d; i++) {37 arr[i] = temp[i];38 }39}4041int main() {42 int arr1[] = {1, 2, 3, 4, 5, 6, 7};43 int arr2[] = {1, 2, 3, 4, 5, 6, 7};44 int n = 7, d = 2;45 46 printf("Original: ");47 for (int i = 0; i < n; i++) printf("%d ", arr1[i]);48 49 rotateLeft(arr1, n, d);50 printf("\nLeft rotate by %d: ", d);51 for (int i = 0; i < n; i++) printf("%d ", arr1[i]);52 53 rotateRight(arr2, n, d);54 printf("\nRight rotate by %d: ", d);55 for (int i = 0; i < n; i++) printf("%d ", arr2[i]);56 printf("\n");57 58 return 0;59}Output
Original: 1 2 3 4 5 6 7
Left rotate by 2: 3 4 5 6 7 1 2
Right rotate by 2: 6 7 1 2 3 4 5
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials