Q:

C++ program to print the left Rotation of the array

belongs to collection: C++ programs on various topics

0

C++ program to print the left Rotation of the array

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ program to check if number is power of 2 using... >>
<< iswupper() function in C++...