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:

  1. We start with an array
  2. State the size and number of rotations to be performed
  3. Use the function left_rotate with 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

Your email address will not be published. Required fields are marked *