Array Rotation - Program For Left and Right Rotation of An Array - Faceprep PROcoder
Array Rotation - Program For Left and Right Rotation of An Array - Faceprep PROcoder
Array Rotation simply means shifting the array elements to the left or right of the array by speci ed
positions. An array can be rotated to the left(clockwise) or to the right (anti-clockwise) to the given number
of positions. Now let us look at a program for left rotation of an array and right rotation of an array.
Left Rotation of Array
Left rotation of an array means shifting of the elements in an array towards the left as shown in the below
image. Left rotation means rotating the elements of the array in a clockwise direction to the speci ed
number of positions.
#include <bits/stdc++.h>
using namespace std;
void left_rotate_by_one(int arr[], int n)
{
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]); // Finding the size of the array
cout<<"\nArray elements before rotating : \n";
for(int i = 0; i < n; i++)
{
cout<<arr[i]<<"\t"; // Printing the array elements
}
int no_of_rotations = 1; // Number of rotations to take place
array_left_rotate(arr, no_of_rotations, n);
cout<<"\n\nArray elements after rotating : \n";
for(int i = 0; i < n; i++)
{
cout<<arr[i]<<"\t"; // Printing the array elements after rotation of elements
}
cout<<"\n";
return 0;
}
# Main Function
import array as arr
arr = arr.array('i', [1,2,3,4,5,6,7])
n = len(arr)
no_of_rotations = 1
print("Array Elements before rotation : ") # printing array before rotating
for i in range (0, n):
print (arr[i], end = ' ')
leftRotate(arr, no_of_rotations, n )
print("\nArray Elements after rotation : ") # printing array after rotating
for i in range (0, n):
print (arr[i], end = ' ')
OUTPUT
Right Rotation of Array
Right rotation of an array means rotating the array elements towards the right of the array as shown in the
below image. Right rotation means rotating the elements of the array in the anti-clockwise direction to the
speci ed number of positions.
#include <bits/stdc++.h>
using namespace std;
void right_rotate_by_one(int arr[], int n)
{
# Main Function
import array as arr
arr = arr.array('i', [1,2,3,4,5,6,7])
OUTPUT
Relevant exercises
Post comment
Languages Languages