Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Circular Rotation of an array

C++ program for the circular rotation of an array by K positions

In this article we’ll be learning about Circular array rotation which means rotating the elements in the array where one rotation operation moves the last element of the array to the first position and shifts all remaining elements to the right. The example for it is given below.

Circular Rotation of an Array in C++ 9

Example 

Let’s we have an array A[ ] = {1, 2, 3, 5} and K = 2 then,

  • After 1 rotation : A[ ] = {5, 1, 2, 3}
  • After 2 rotation : A[ ] = {3, 5, 1, 2}

Algorithm :

  • By reversing the array we can circularly rotates the array.
  • First we will set K to points that element which comes at first position, i.e. K = N-K.
  • Then , reverse the array from 0 to K-1 position.
  • After that, again reverse the array from K to N-1 position.
  • And then finally reverse the entire array.
  • Doing so we will get the desired circularly rotated array by K position.
 
 

C++ program for Circular Rotation of an Array :

#include<bits/stdc++.h>
using namespace std;

int main ()
{

int n; // variable to store the size of the array
int k; // variable to store the position for rotation

cout << "Enter the size of array : ";
cin >> n;

cout << "\nEnter the position for rotation : ";
cin >> k;

std::vector < int >A (n); // declaring a vector of size n

cout << "\nEnter the elements of the array : ";

for (int i = 0; i < n; i++)
cin >> A[i];

k = (n - k) % n; // set k to the index which comes first

reverse (A.begin (), A.begin () + k); //reverse the array from 0 to k position
reverse (A.begin () + k, A.end ()); //reverse the array from k to n-1 position
reverse (A.begin (), A.end ()); //reverse the array from 0 to n-1 position

cout << "\nArray after rotation: ";

for (int i = 0; i < n; i++)
cout << A[i] << " ";

return 0;

}
Output :
Enter the size of array : 5

Enter the position for rotation : 2

Enter the elements of array : 1 2 3 4 5

Array after rotation : 4 5 1 2 3