C program to perform left rotation of array elements by two positions

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

Our problem statement

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

Program in C to perform left rotation by 2

#include <stdio.h>

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

    printf("=== C Program to perform two-time left 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 left rotation two times
    for(i = 0; i < 2; i++) {
        temp = array[0];
        for(j = 0; j < arraySize - 1; j++) {
            array[j] = array[j + 1];
        }
        array[arraySize - 1] = temp;
    }

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

    return 0;
}

Output

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

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

Similar Reads

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