C program to perform right rotation in array by 2 positions

Performing right rotation in array means, our last element will become first element and shift each array elements towards right by one. Here we are going to perform right rotation by 2 times means we will shift each array element toward right two times.

Our problem statement

Suppose we have an array that has elements a={1,2,3,4,5}. As we have to perform right rotation in array, after first time right rotation element will become {5,1,2,3,4}. Now after performing right rotation again, I mean 2nd time, array will become {4,5,1,2,3}. So this the exact output which we want by our program for an input array.

C Program to perform right rotation by 2 in array

#include <stdio.h>

int main() {
    int i, arraySize, j, temp;

    printf("=== C Program to perform two-time right rotation ===\n\n");
    printf("Enter the number of elements you want in the array: ");
    scanf("%d", &arraySize);

    int array[arraySize];

    // Taking input for the array
    for(i = 0; i < arraySize; i++) {
        printf("Enter value for index %d: ", i);
        scanf("%d", &array[i]);
    }

    // Perform right rotation two times
    for(i = 0; i < 2; i++) {
        temp = array[arraySize - 1];
        for(j = arraySize - 1; j > 0; j--) {
            array[j] = array[j - 1];
        }
        array[0] = temp;
    }

    // Display the rotated array
    printf("Array after two-time right rotation:\n");
    for(i = 0; i < arraySize; i++) {
        printf("%d ", array[i]);
    }

    return 0;
}

Output

=== C Program to perform two-time right rotation ===

Enter the number of elements you want in the array: 5
Enter value for index 0: 4
Enter value for index 1: 1
Enter value for index 2: 2
Enter value for index 3: 33
Enter value for index 4: 1
Array after two-time right rotation:
33 1 4 1 2
What did you think?

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now