Write a C program to rotate an array right by n places.
#include <stdio.h>
#define MAX 256
int main() {
int i, j, n, temp, shift, array[MAX];
/* get the number of array entries from the user */
printf("Enter the number of elements in input array:");
scanf("%d", &n);
/* get the array entries from the user */
printf("Enter your array entries:\n");
for (i = 0; i < n; i++) {
printf("Array[%d]: ", i);
scanf("%d", &array[i]);
}
/* get the rotation input from the user */
printf("Rotate the array elements right by ");
scanf("%d", &shift);
/* rotate the given array right by given place */
for (i = 0; i < shift; i++) {
temp = array[n - 1];
for (j = n - 1; j >= 1; j--) {
array[j] = array[j - 1];
}
array[0] = temp;
}
/* print the resultant array */
printf("\nResultant array:\n");
for (i = 0; i < n; i++) {
printf("%d ", array[i]);
}
#define MAX 256
int main() {
int i, j, n, temp, shift, array[MAX];
/* get the number of array entries from the user */
printf("Enter the number of elements in input array:");
scanf("%d", &n);
/* get the array entries from the user */
printf("Enter your array entries:\n");
for (i = 0; i < n; i++) {
printf("Array[%d]: ", i);
scanf("%d", &array[i]);
}
/* get the rotation input from the user */
printf("Rotate the array elements right by ");
scanf("%d", &shift);
/* rotate the given array right by given place */
for (i = 0; i < shift; i++) {
temp = array[n - 1];
for (j = n - 1; j >= 1; j--) {
array[j] = array[j - 1];
}
array[0] = temp;
}
/* print the resultant array */
printf("\nResultant array:\n");
for (i = 0; i < n; i++) {
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the number of elements in input array:5
Enter your array entries:
Array[0]: 10
Array[1]: 20
Array[2]: 30
Array[3]: 40
Array[4]: 50
Rotate the array elements right by 2
Resultant array:
40 50 10 20 30
Enter the number of elements in input array:5
Enter your array entries:
Array[0]: 10
Array[1]: 20
Array[2]: 30
Array[3]: 40
Array[4]: 50
Rotate the array elements right by 2
Resultant array:
40 50 10 20 30
No comments:
Post a Comment