Saturday, June 19, 2021
Home coding Write a program to rotate an array.

# Write a program to rotate an array.

Given a integer array,we have to rotate an array on left position and print the result of rotate of array.

Example:

``````input:1 2 3 4 5 6   k=1
output:2 3 4 5 6 1
``````

Logic:

``````Step 1-left rotation of array shifting the element in the array toward left.
step 2-rotate an array by using temp variable .
step 3-call the rotation function to rotate the array for k position.``````

Code-

```#include <bits/stdc++.h>
using namespace std;
void rotate(int arr[], int n)
{
int temp = arr[0], i;
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[i] = temp;
}
void rotation(int arr[], int k, int n)
{
for (int i = 0; i < k; i++)
rotate(arr, n);
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
int k=2;
rotation(arr, k, n);
cout<<"after rotation"<<endl;
for(int i = 0; i < n; i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;

}```

Output:

```after rotation
3 4 5 6 7 1 2
```

Time complexity:0(N)

Space Complexity:O(1)