C Program To Left Rotate The Elements Of An Array

If the value of n is 1, each element in the array will shift one position to the left. This means that the second element will become the first, the third element will move to the second position, and so forth. Simultaneously, the original first element will be appended to the end of the array.

ALGORITHM:

  • STEP 1: START
  • STEP 2: INITIALIZE arr ={1, 2, 3, 4, 5 }.
  • STEP 3: length = sizeof(arr1)/sizeof(arr1[0])
  • STEP 4: length = sizeof(arr)/sizeof(arr[0])
  • STEP 5: SET n =3
  • STEP 6: SET i=0. REPEAT STEP 7 to STEP 8 UNTIL i<length
  • STEP 7: PRINT arr[i]
  • STEP 8: i = i+1
  • STEP 9: SET i= 0. REPEAT STEP 10 to STEP 16 UNTIL i<n
  • STEP 10: DEFINE j, first.
  • STEP 11: first = arr[0]
  • STEP 12: SET j=0. REPEAT STEP 13 to STEP 14 UNTIL j<length-1.
  • STEP 13: arr[j]= arr[j+1]
  • STEP 14: j=j+1.
  • STEP 15: arr[j]= first
  • STEP 16: i=i+1.
  • STEP 17: PRINT new line.
  • STEP 18: PRINT "Array after left rotation"
  • STEP 19: ENDSET i=0. REPEAT STEP 20 to STEP 21 UNTIL i<length
  • STEP 20: PRINT arr[i]
  • STEP 21: i=i+1.
  • STEP 22: RETURN 0.
  • STEP 23: END
  • PROGRAM:

    Example
    
    #include <stdio.h>  
    
       
    
    int main()  
    
    {  
    
        //Initialize array   
    
        int arr[] = {1, 2, 3, 4, 5};   
    
        //Calculate length of array arr  
    
        int length = sizeof(arr)/sizeof(arr[0]);  
    
        //n determine the number of times an array should be rotated  
    
        int n = 3;  
    
          
    
        //Displays original array  
    
        printf("Original array: \n");  
    
        for (int i = 0; i < length; i++) {   
    
            printf("%d ", arr[i]);   
    
        }    
    
          
    
        //Rotate the given array by n times toward left  
    
        for(int i = 0; i < n; i++){  
    
            int j, first;  
    
            //Stores the first element of the array  
    
            first = arr[0];  
    
          
    
            for(j = 0; j < length-1; j++){  
    
                //Shift element of array by one  
    
                arr[j] = arr[j+1];  
    
            }  
    
            //First element of array will be added to the end  
    
            arr[j] = first;  
    
        }  
    
          
    
        printf("\n");  
    
          
    
        //Displays resulting array after rotation  
    
        printf("Array after left rotation: \n");  
    
        for(int i = 0; i < length; i++){  
    
            printf("%d ", arr[i]);  
    
        }  
    
        return 0;  
    
    }
    

Output:

Output

Original Array:

1   2   3   4   5

Array after left rotation:

4   5   1   2   3

Input Required

This code uses input(). Please provide values below: