cyclically rotate an array by one

Cyclically Rotate an Array by One

To cyclically rotate an array by one, we need to move each element of the array one position to the right, with the last element moving to the first position. Here's the step-by-step explanation:

  1. Declare and Initialize the Array: Start by declaring and initializing the array with the desired elements. For example, let's consider an array arr with elements [1, 2, 3, 4, 5].

  2. Store the Last Element: Store the last element of the array in a temporary variable. In our example, the last element is 5.

  3. Shift Elements to the Right: Iterate through the array from the second-to-last element to the first element. Move each element one position to the right by assigning the value of the previous element to the current element's position. In our example, we would move 4 to the position of 5, 3 to the position of 4, and so on.

  4. Assign the Stored Element to the First Position: Assign the stored last element to the first position of the array. In our example, assign 5 to the first position of the array.

  5. Print the Rotated Array: Finally, print the rotated array. In our example, the rotated array would be [5, 1, 2, 3, 4].

Here's the code implementation in C:

#include <stdio.h>

void rotateArray(int arr[], int size) {
    int lastElement = arr[size - 1];

    for (int i = size - 1; i > 0; i--) {
        arr[i] = arr[i - 1];
    }

    arr[0] = lastElement;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);

    printf("Original Array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }

    rotateArray(arr, size);

    printf("\nRotated Array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

Output:

Original Array: 1 2 3 4 5
Rotated Array: 5 1 2 3 4

This code rotates the array arr by one position to the right and prints the original and rotated arrays.