In this example, You learn about c++ program to left rotation of array.
C++ Program to Left Rotation of Array
Output
I hope you enjoy this example if you have doubt leave it in the comment box below.
Happy Coding 😊
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.
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;
}
Array Before Left Rotation: 11 22 33 44 55 Array After Left Rotation: 22 33 44 55 11
Happy Coding 😊