可以通過以下代碼將一個數組逆序排列:
#include <stdio.h>
void reverseArray(int arr[], int size) {
int start = 0;
int end = size - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
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