Question -
Given an array, cyclically rotate the array clockwise by d.
Example -
Input : arr[] = {1,2,3,4,5} , d=2
output : {4,5,1,2,3}
Solution -
//first we initilize last element of array in temporary variable and then shift all element to right side and atlast we initilize first variable of array with temp...thats solve
#include<iostream>
using namespace std;
void rotatearray(int arr[],int n)
{
int temp=arr[n-1];
for(int i=n-1;i>0;i--){
arr[i]=arr[i-1];
}
arr[0]=temp;
}
int main()
{
int n;cout<<"Enter the no of elements : ";cin>>n;
int d;cout<<"Enter the no of rotations : ";cin>>d;
int arr[n];cout<<"Enter "<<n<<" elements : "<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
d%=n;
for(int i=0;i<d;i++)
rotatearray(arr,n);
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
return 0;
}
Comments
Post a Comment