Skip to main content

Reverse array and display via pointer

Short answer

Function reverseArray uses two pointers (start and end). While i < j, swap *i and *j, then move pointers inward. It returns the array pointer. Main calls it, then prints reversed elements using *(p+i). Example output: 5 4 3 2 1.

Write a C program that calls reverse array () to reverse the array and return the array and display the element of reversed array using pointer.

Logic. reverseArray(int *a, int n) uses two pointers: i at the first element and j at the last (a + n - 1). While i < j the values *i and *j are swapped, then i moves forward and j backward. The function returns the pointer to the array, and main() displays the reversed elements with *(p + i).

#include <stdio.h>

/* reverses the array in place and returns its address */
int *reverseArray(int *a, int n)
{
    int *i = a, *j = a + n - 1, t;
    while (i < j) {
        t = *i; *i = *j; *j = t;
        i++; j--;
    }
    return a;
}

int main(void)
{
    int a[50], n, *p;
    printf("Enter N: ");
    scanf("%d", &n);
    printf("Enter %d elements: ", n);
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]);

    p = reverseArray(a, n);
    printf("Reversed array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", *(p + i));
    printf("\n");
    return 0;
}

Sample run

Input: 5 1 2 3 4 5

Enter N: Enter 5 elements: Reversed array: 5 4 3 2 1

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 9 questions →