A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

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

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

0

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: Nd 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

 

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)

Similar questions


need a help?


find thousands of online teachers now