LearnFrenzy
Sign in Take a free test

Pointers · Pointer Programs · Question 3

C program to reverse an array using pointers Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Reverse an integer array in place using two pointers, one from each end.

Solution
main.c
#include <stdio.h>

void reverse(int *a, int n) {
    int *left = a, *right = a + n - 1;
    while (left < right) {
        int t = *left;
        *left++ = *right;
        *right-- = t;
    }
}

int main(void) {
    int a[] = {1, 2, 3, 4, 5, 6};
    int n = sizeof a / sizeof a[0];
    reverse(a, n);
    for (int i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}

Output Verified by compiling and running

6 5 4 3 2 1

Swap the elements at the two pointers, then move them towards each other until they meet: n/2 swaps, no second array. *left++ = *right stores, then moves left forward.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Popular