C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Rotate Array to the Left

C Program: Rotate Array to the Left

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 left: ");

    scanf("%d", &rotate);

 

    // Perform left rotation

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

        temp = arr[0];

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

            arr[i] = arr[i + 1];

        }

        arr[n - 1] = temp;

    }

 

    // Display result

    printf("\nArray after left 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 left: 2

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

Explanation

  1. The program reads an array and the number of positions to rotate.
  2. Each rotation moves the first element to the end of the array.
  3. The inner loop shifts elements left by one position.
  4. After all rotations, the rotated array is printed.