31. Reverse an Array Using Only Pointers

#include <stdio.h>

// Function to reverse array using only pointers
void reverse_array(int *ptr, int n) {
    int *start = ptr;          // Pointer to first element
    int *end = ptr + n - 1;     // Pointer to last element

    while (start < end) {
        int temp = *start;
        *start = *end;
        *end = temp;

        start++;
        end--;
    }
}

int main() {
    int n;
    scanf("%d", &n);

    int arr[100];
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    reverse_array(arr, n);

    for (int i = 0; i < n; i++) {
        printf("%d", arr[i]);
        if(i < n-1){
            printf(" ");
        }
    }

    return 0;
}
  • Start points to the first element; end points to the last.
  • Swap the values at start and end using dereferencing.
  • Move start++ forward and end-- backward until they meet or cross.
  • No array indexing is used — only pointer movements and dereferencing.

 

Loading...

Input

5 1 2 3 4 5

Expected Output

5 4 3 2 1