C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Rotate Array to the Right

C Program: Rotate Array to the Right

C

#include <stdio.h>

 

int main() {

    int arr[100], n, i, j, temp, rotate;

 

    // Input number of elements

    printf("Enter number of elements in the array: ");

    scanf("%d", &n);

 

    // Input array elements

    printf("Enter %d elements:\n", n);

    for (i = 0; i < n; i++) {

        scanf("%d", &arr[i]);

    }

 

    // Input number of rotations

    printf("Enter number of times to rotate right: ");

    scanf("%d", &rotate);

 

    // Perform right rotation

    for (j = 0; j < rotate; j++) {

        temp = arr[n - 1];

        for (i = n - 1; i > 0; i--) {

            arr[i] = arr[i - 1];

        }

        arr[0] = temp;

    }

 

    // Display result

    printf("\nArray after right rotation:\n");

    for (i = 0; i < n; i++) {

        printf("%d ", arr[i]);

    }

 

    return 0;

}

Output

 
INPUT :
Enter number of elements in the array: 5
Enter 5 elements:
1 2 3 4 5
Enter number of times to rotate right: 2

OUTPUT :
Array after right rotation:
4 5 1 2 3

Explanation

  1. The program reads an array and the number of rotations.
  2. For each rotation, the last element is stored temporarily.
  3. All other elements are shifted one position to the right.
  4. The stored element is placed at the first position.
  5. After all rotations, the array is displayed.