可以通過循環遍歷數組,依次交換首尾元素的方式來逆序數組。具體代碼如下:
#include <stdio.h>
void reverseArray(int arr[], int size) {
int temp;
for (int i = 0; i < size / 2; i++) {
temp = arr[i];
arr[i] = arr[size - 1 - i];
arr[size - 1 - i] = temp;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
reverseArray(arr, size);
printf("\nReversed array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
運行結果:
Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1