Rotate the elements of an array in right
C program to cyclically permute (rotate) the elements of an array in right.
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_right(int a[MAX], int n, int count)
{
int i, j, last;
for(i=0;i<count;i++)
{
last = a[n-1];
for(j=n-1;j>0;j--)
{
a[j] = a[j-1];
}
a[0] = last;
}
}
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 right\t:");
scanf("%d",&count);
rotate_right(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 :87
Element 7 :74
Element 8 :41
Enter the number of times to rotate right :4
Rotated array
Element 1 :98
Element 2 :87
Element 3 :74
Element 4 :41
Element 5 :12
Element 6 :25
Element 7 :56
Element 8 :69