求将一个数组中的值按逆序重新存放,例如,原来顺序为8,6,5,4,1。要求改为1,4,5,6,8的c语言程序
时间: 2023-08-08 15:07:59 浏览: 75
可以使用双指针的方法,将数组头尾元素交换,直到两个指针相遇。以下是代码示例:
```c
#include <stdio.h>
void reverseArray(int arr[], int length) {
int left = 0;
int right = length - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
int main() {
int arr[] = {8, 6, 5, 4, 1};
int length = sizeof(arr) / sizeof(int);
printf("Original array: ");
for (int i = 0; i < length; i++) {
printf("%d ", arr[i]);
}
reverseArray(arr, length);
printf("\nReversed array: ");
for (int i = 0; i < length; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
输出结果为:
```
Original array: 8 6 5 4 1
Reversed array: 1 4 5 6 8
```
阅读全文