Array rotation (method -1)

Question - 

Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements.

Example - 

Input : arr[]={1,2,3,4,5,6,7} , d=2, n=7

Output  : {2,3,4,5,6,7,1,2}

Solution : 


//In this method we take first number of array in temporary variable and rotate each element left side and atleast we assign last element with temporary variable and do this  process d times. 


#include<iostream>

using namespace std;

void print(int arr[],int n)

{

   for (int i = 0; i < n; i++)

   {

      cout<<arr[i];

   }

}

int main()

{

   int n;

   cout<<"Enter size of array : ";

   cin>>n;

   int d;

   cout<<"Enter value of d : ";

   cin>>d;

  if(d>n)

    d%=n;


   int arr[n];

   cout<<"Enter element of Array : "<<endl;

   for(int i=0;i<n;i++)

    cin>>arr[i];

   // print(arr,n);

   for (int  i = 0; i < d; i++)

   {

      int temp=arr[0];

      for (int j=0;j<n;j++)

      {

          arr[j]=arr[j+1]; 

      }

      arr[n-1]=temp;

      

   }

   

   print(arr,n);


   

}

Time complixity - O(n*d)


Compiler link with code

Comments