C语言 编写一程序,将长度为n的一位数组各个元素向前移动m个位置,最前面的m个元素变成最后的m个数。要求数据处理用函数实现 数据的输入和输出在主函数中进行。
时间: 2023-07-16 10:16:11 浏览: 33
下面是一个简单的C语言程序,实现了将数组元素向前移动m个位置的功能:
```c
#include <stdio.h>
void shift_array(int arr[], int n, int m);
int main() {
int n, m, i;
printf("Enter the length of the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements of the array: ");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the number of positions to shift: ");
scanf("%d", &m);
shift_array(arr, n, m);
printf("The shifted array is: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
void shift_array(int arr[], int n, int m) {
int temp[m];
int i, j;
for (i = 0; i < m; i++) {
temp[i] = arr[i];
}
for (i = m; i < n; i++) {
arr[i-m] = arr[i];
}
for (i = n-m, j = 0; i < n; i++, j++) {
arr[i] = temp[j];
}
}
```
函数 `shift_array` 接受三个参数:数组 `arr`、数组长度 `n` 和移动的位置数 `m`。在该函数中,我们首先创建一个长度为 `m` 的临时数组 `temp`,将原数组的前 `m` 个元素复制到 `temp` 数组中。然后,我们将原数组中的元素向前移动 `m` 个位置,覆盖掉前 `m` 个元素。最后,我们将 `temp` 数组中的元素复制回原数组的末尾 `m` 个位置。
在 `main` 函数中,我们首先读入数组的长度和元素,然后读入需要移动的位置数。接下来,我们调用 `shift_array` 函数对数组进行移动操作,并输出移动后的数组。