# Array Rotation in C

0 728

##
**Introduction to Array Rotation in C
**

Array rotation is a fundamental** operation** in programming, especially in **array manipulation tasks**.

It involves** shifting **the elements of an** array cyclically** to the** left** or** right**.

This** operation **finds applications in various domains, including image processing, cryptography, and algorithm design.

Original Array: [1, 2, 3, 4, 5] After Left Rotation by 2: [3, 4, 5, 1, 2] After Right Rotation by 3: [3, 4, 5, 1, 2]

**Example:
**

// Program for Array Rotation in C #include<stdio.h>// Function to rotate an array to the left by 'd' positions void leftRotate(int arr[], int n, int d) { int temp[d]; for (int w1 = 0; w1 < d; w1++) temp[i] = arr[i]; for (int w1 = d; w1 < n; w1++) arr[w1 - d] = arr[w1]; for (int w1 = 0; w1 < d; w1++) arr[n - d + w1] = temp[w1]; } // Function to rotate an array to the right by 'd' positions void rightRotate(int arr[], int n, int d) { int temp[d]; for (int w1 = n - d; w1 < n; w1++) temp[w1 - (n - d)] = arr[w1]; for (int w1 = n - d - 1; w1 >= 0; w1--) arr[w1 + d] = arr[w1]; for (int w1 = 0; w1 < d; w1++) arr[i] = temp[i]; } // Function to print an array void printArray(int arr[], int n) { for (int w1 = 0; w1 < n; w1++) printf("%d ", arr[w1]); printf("\n"); } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); int d = 2; // Number of positions to rotate printf("Original Array: "); printArray(arr, n); leftRotate(arr, n, d); printf("After Left Rotation by %d: ", d); printArray(arr, n); rightRotate(arr, n, d); printf("After Right Rotation by %d: ", d); printArray(arr, n); return 0; }

**Output:
**

Original Array: 1 2 3 4 5 After Left Rotation by 2: 3 4 5 1 2 After Right Rotation by 2: 1 2 3 4 5

This program defines two functions, **leftRotate()** and** rightRotate()**, to perform left and right rotations, respectively, on an **array**.

The** printArray()** function is used to **display** the **array elements**.

In the** main() function**, an** array **is **initialized**, and **rotation**s are performed and printed to demonstrate the** functionality**.

Share:

## Comments

Waiting for your comments