How to reverse output an array in the C language?
You can use a loop to print the array in reverse order.
Here are the specific steps:
- First, define an array to store numbers, let’s assume it is called arr.
- Initialize two variables, start and end, pointing to the first and last elements of the array, respectively.
- Using a loop, swap elements pointed to by start and end, then move start one position backwards and end one position forward until start is greater than or equal to end.
- After the loop ends, the entire array will be reversed and outputted.
Here is a sample code:
#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]);
reverseArray(arr, size);
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
The output is: 5 4 3 2 1