Skip to main content

Rotating an Array

Task: Rotate an array of size N by d elements, where d <= N.

Example:
Input:
1
1 2 3 4 5
Output:
3 4 5 1 2


Here is the Code:

Program in C++:

  1. #include<iostream>
  2. using namespace std;
  3. int main()
  4.  {
  5. int t;
  6. cin>>t;
  7. while(t--)
  8. {
  9.     int n;
  10.     cin>>n;
  11.     int a[n];
  12.     for(int i=0;i<n;i++)
  13.     {
  14.         cin>>a[i];
  15.     }
  16.     int d;
  17.     cin>>d;
  18.     // code logic
  19.     for(int i=0;i<d;i++)
  20.     {
  21.         int j=0,temp=a[0];
  22.         while(j<n-1)
  23.         {
  24.             a[j]=a[j+1];
  25.             j++;
  26.         }
  27.         a[j]=temp;
  28.     }
  29.     for(int i=0;i<n;i++)
  30.     {
  31.         cout<<a[i]<<" ";
  32.     }
  33.     cout<<endl;
  34. }
  35. return 0;
  36. }

Here is the Video: