Cover Image for Reverse an Array in C
143 views

Reverse an Array in C

To reverse an array in C, you can swap elements from the beginning of the array with elements from the end of the array until you reach the middle of the array. Here’s a C program to reverse an array:

C
#include <stdio.h>

void reverseArray(int arr[], int start, int end) {
    while (start < end) {
        // Swap the elements at the start and end positions
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

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

    printf("Original Array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    // Reverse the array
    reverseArray(arr, 0, n - 1);

    printf("Reversed Array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}

In this program:

  • The reverseArray function takes an array arr, a starting index start, and an ending index end. It swaps elements at start and end, then moves start one step to the right and end one step to the left. This process is repeated until start is greater than or equal to end.
  • In the main function, we initialize an array, print the original array, call reverseArray to reverse the array, and then print the reversed array.

When you run this program, it will reverse the elements of the array, resulting in the reversed order.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS