Reverse Array in C: Store Numbers Backward
To store a set of numbers in reverse order, you can achieve this by swapping the elements in the array. The specific steps are as follows:
- Declare an integer array to store the numbers to be reversed.
- Reverse the elements of an array by using a loop. Iterate through half of the array’s length, starting from both ends and swapping elements until reaching the middle position.
- Create a temporary variable and determine the length of the integer array. Then, iterate through half of the array swapping elements from the beginning with elements from the end.
- After the loop, the elements in the array are stored in reverse order.
Complete code example:
#include <stdio.h>
int main() {
int array[] = {1, 2, 3, 4, 5};
int length = sizeof(array) / sizeof(int);
// 交换数组元素
int temp;
for (int i = 0; i < length / 2; i++) {
temp = array[i];
array[i] = array[length - i - 1];
array[length - i - 1] = temp;
}
// 输出逆序后的数组
for (int i = 0; i < length; i++) {
printf("%d ", array[i]);
}
return 0;
}
The output is: 5 4 3 2 1.