How to print the left rotated array in C++
In this C++ article, given an array of size N, we have to print the elements of the left rotated array by d positions.
Let’s take the help of an example.
Input:
n = 7, d = 2
array: 1 2 3 4 5 6 7
Output: 3 4 5 6 7 1 2
Printing the left rotated array using C++
Code Implementation for our task:
#include <iostream> using namespace std; int main() { int n,d; cout<<"Enter the value of n and d"<<endl; cin>>n>>d; int a[n]; cout<<"enter the array elements : "; for(int i=0;i<n;i++) { cin>>a[i]; } 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
Working :
The general approach to solve this problem is to shift the elements d times but this is a time-consuming process. To avoid this, we follow a different strategy.
Let, ‘i’ be the ith iteration, D be the number of elements to rotate and N be the size of the array.
Then to rotate the array to its left, we can use, arr[i] = arr[(i+D)%N], this creates a new array from index 3 of the original array as i=0. Thus in the above example the value at index 3, i.e 4 becomes the first element of the left rotated array. This runs as a loop for every index in the loop.
I hope, you have understood how our program works to print the left rotated array in C++ language.
Mention below your comments, if you find any mistake in the article or to share more information related to the topic of this article.
You may also learn,
Leave a Reply