Examples:
Input:
arr[ ]= {1,2,3,4,5,6}
d = 3
Output:
arr[ ] = {4,5,6,1,2,3}
Input:
arr[ ]= {1, 2, 3, 4, 5, 6}
d = 2
Output:
arr[ ]= {3, 4, 5, 6, 1, 2}
#include <bits/stdc++.h>
using namespace std;
// Function to rotate the arr once
void rotateOnce(int arr[], int n)
{
int temp = arr[0];
for (int i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[n - 1] = temp;
}
// Function to perform one rotate
// d times
void rotate(int arr[], int d, int n)
{
for (int i = 0; i < d; i++)
rotateOnce(arr, n);
}
// Function to print the arr
void printarr(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
// Main function
int main()
{
int arr[100], N, d;
cout << "Enter Number of elements: ";
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> arr[i];
}
cout << "Enter the value of d: ";
cin >> d;
rotate(arr, d, N);
cout << "Rotated arr" << endl;
printarr(arr, N);
return 0;
}
Output:
Enter Number of elements: 5
1 2 3 4 5
Enter the value of d: 3
Rotated array :
4 5 1 2 3
0 Comments