Reverse Array in C: Simple Method & Code
To reverse the elements of a C language array, you can achieve this by using a loop and a temporary variable. The specific steps are as follows:
- Define a temporary variable called temp.
- Iterate through the array using a loop and exchange elements from both ends towards the middle sequentially.
- The loop condition can be set for i to start at 0 and increment, and for j to start at the array length minus 1 and decrement, until i is greater than or equal to j.
- Within the loop, assign the value of arr[i] to temp, then assign the value of arr[j] to arr[i], and finally assign the value of temp to arr[j], completing the element swap.
- After the loop ends, the elements of the array are reversed.
Here is an example of the code:
#include <stdio.h>
void reverseArray(int arr[], int n) {
int i, j, temp;
for (i = 0, j = n-1; i < j; i++, j--) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("原数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
reverseArray(arr, n);
printf("\n逆置后的数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Result of operation:
原数组:1 2 3 4 5
逆置后的数组:5 4 3 2 1