Quickly find multiple left rotations of an array using C++
The multiple left rotations mean rotating an array n number of times.
For eg: array: 1,2,3,4,5
rotating 3 times: 4 5 1 2 3
C++ Code for multiple left rotations
For having multiple rotations of an array, we use the following method:
Steps:
- We start with an array
- State the size and number of rotations to be performed
- Use the function
left_rotatewith its parameters: array, size, and no of rotations(n), it prints the array starting with index n and continuing the indices as i%size
We can use the following code:
#include <iostream>
using namespace std;
void left_rotate(int arr[], int n,int size)
{
cout<<n <<" rotated array:"<<endl;
for (int i = n; i < size+ n; i++)
cout << arr[i%size] << " ";
}
int main()
{
int array[]={1,2,3,4,5};
int n,s;
s=sizeof(array)/4;
cout<<"no of rotation: ";
cin>>n;
left_rotate(array,n,s);
return 0;
}
Output:
no of rotation: 3 4 5 1 2 3
Leave a Reply