C语言代码实现把一个有n个元素的数组循环向右移动m位
时间: 2024-04-17 20:26:50 浏览: 30
可以使用以下C语言代码实现将一个有n个元素的数组循环向右移动m位:
```c
#include <stdio.h>
void rotateArray(int arr[], int n, int m) {
int temp[m];
// 将需要移动的元素保存到临时数组
for (int i = 0; i < m; i++) {
temp[i] = arr[n - m + i];
}
// 将数组右移m位
for (int i = n - 1; i >= m; i--) {
arr[i] = arr[i - m];
}
// 将临时数组中的元素放回原数组的前面
for (int i = 0; i < m; i++) {
arr[i] = temp[i];
}
}
int main() {
int n, m;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements of the array: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the number of positions to rotate: ");
scanf("%d", &m);
rotateArray(arr, n, m);
printf("Array after rotating %d positions to the right: ", m);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
该代码首先定义了一个名为`rotateArray`的函数,该函数用于实现循环右移操作。然后,在主函数中,用户需要输入数组的元素个数`n`、数组的元素以及需要移动的位数`m`。接下来,调用`rotateArray`函数对数组进行循环右移操作,并最后输出移动后的数组。