Rotate the elements of an array in left
C program to cyclically permute (rotate) the elements of an array in left.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void read_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:",i+1);
scanf("%d",&a[i]);
}
}
void print_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:%d\n",i+1,a[i]);
}
}
void rotate_left(int a[MAX], int n, int count)
{
int i, j, first;
for(i=0;i<count;i++)
{
first = a[0];
for(j=0;j<n-1;j++)
{
a[j] = a[j+1];
}
a[n-1] = first;
}
}
void main()
{
int arr[MAX];
int n, count;
printf("Enter the number of elements in the array\t:");
scanf("%d",&n);
printf("Enter the elements of the array\n");
read_array(arr, n);
printf("Enter the number of times to rotate left\t:");
scanf("%d",&count);
rotate_left(arr, n, count);
printf("\nRotated array\n");
print_array(arr, n);
getch();
}
Output
Enter the number of elements in the array :8
Enter the elements of the array
Element 1 :12
Element 2 :25
Element 3 :56
Element 4 :69
Element 5 :98
Element 6 :85
Element 7 :54
Element 8 :41
Enter the number of times to rotate left :4
Rotated array
Element 1 :98
Element 2 :85
Element 3 :54
Element 4 :41
Element 5 :12
Element 6 :25
Element 7 :56
Element 8 :69