Home »
C++ programs
C++ program to print the left Rotation of the array
Left rotation of the array using C++ program: Here, we are going to learn how to print the array elements after left rotation?
Submitted by Vivek Kothari, on February 13, 2019
Problem statement:
Given an array of N elements and the task is to print the elements of an array after left rotating array elements by d positions.
Input: N, d and next line containing the n elements of array.
Output: Array elements after d rotation.
Example:
Input:
n = 7, d = 2
array elements: 1 2 3 4 5 6 7
Output:
3 4 5 6 7 1 2
Solution:
The naïve approach to solve this problem is to shift the all elements d times but this is a time-consuming process.
We can use a small trick here to print the elements of the array after left rotating d elements.
Let,
i = ith iteration
D = number of elements to rotate
N = size of array
Then to left rotate array we can use -
arr[i] = arr[(i+D)%N]
C++ Implementation:
#include <iostream>
using namespace std;
int main()
{
int n,d;
//input value of n and d
cout<<"Enter the value of n and d"<<endl;
cin>>n>>d;
int a[n];
//input array elements
cout<<"enter the array elements : ";
for(int i=0;i<n;i++)
{
cin>>a[i];
}
//print the elements of array after rotation
cout<<"array elements after rotation : ";
for(int i=0;i<n;i++)
{
cout<<a[(i+d)%n]<<" ";
}
return 0;
}
Output
Enter the value of n and d
7 3
enter the array elements : 1 2 3 4 5 6 7
array elements after rotation : 4 5 6 7 1 2 3