Program for Left Rotation of Array in C++

In this example, You learn about c++ program to left rotation of array.

Here you learn program to left rotation of array in C++, This problem you see on competitive programming websites like leetcode, hackerrank, etc. You have an array and then rotate the array into anti-clockwise direction.
 
 
left rotate array

Explanation

Left rotation of array or rotate array by one in left direction both are same. In this firstly, we save the first element of an array into an temporary space and then shift array elements one by one left side of array and at the end we replace last element of array with temporary element.

C++ Program to Left Rotation of Array

#include<bits/stdc++.h>
using namespace std;  
       
int main()  
{     
    int arr[] = {11, 22, 33, 44, 55}; //Initialization array   
    int len = sizeof(arr)/sizeof(arr[0]);  //Calculate length of array arr 
            
    cout<<"Array Before Left Rotation: \n"; //Displays Array  
    for (int i = 0; i < len; i++) {   
        cout<<arr[i]<<"\t";   
    }    
          
    int j, temp;  
     
    temp = arr[0]; //Stores the first element of the array into temporary space   
          
    for(j = 0; j < len-1; j++){  
      arr[j] = arr[j+1];   //Shift element of array by one  
    }  
    
    arr[j] = temp;  //Now Set temporary element of array to the end  
          
    cout<<"\n";  
           
    cout<<"Array After Left Rotation: \n";  //Displays Resulting Array 
    for(int i = 0; i < len; i++){  
        cout<<arr[i]<<"\t";  
    }  
	return 0;  
}

Output
Array Before Left Rotation:
11      22      33      44      55
Array After Left Rotation:
22      33      44      55      11
I hope you enjoy this example if you have doubt leave it in the comment box below.
Happy Coding 😊

No comments:

Post a Comment

If you have any doubts, Please let me know