How to reverse the order of an array in the C programmi…

One option is to use a loop and a temporary variable to achieve the function of outputting an array in reverse order. The specific steps are as follows:

  1. Define an integer array and initialize it.
  2. Iterate through the array starting from the last element and moving backwards using a loop.
  3. Assign the currently iterated element to a temporary variable within the loop.
  4. Assign the current element being iterated to the element at the corresponding position in the array.
  5. Assign the elements in the array to temporary variables at the corresponding positions.
  6. Repeat steps 2 to 5 until the entire array has been traversed.
  7. Output the elements of the array starting from the first element using a different loop.

Here is an example code snippet:

#include <stdio.h>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int len = sizeof(arr) / sizeof(arr[0]);

    // 将数组逆序
    for (int i = len - 1; i >= len / 2; i--) {
        int temp = arr[i];
        arr[i] = arr[len - 1 - i];
        arr[len - 1 - i] = temp;
    }

    // 输出逆序后的数组
    for (int i = 0; i < len; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

When you run the code above, the output will be: 5 4 3 2 1, which is the reverse of the original array.

bannerAds