All submissions

Reverse an Array Using Only Pointers

Code

#include <stdio.h>

void reverse_array(int *ptr, int n) {
    // Your logic here
    int *p, *q, i, hold;
    p=ptr;
    q= p+n-1;
    for (i=0; i < (n/2); i++) {
        hold= *p;
        *p= *q;
        *q= hold;
        p++;
        --q;
    }
}

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;
}

Solving Approach

 

use two pointers: one to the top of the list and other to the last item.

use a variable to hold value while you swap top and bottom value;

increment the top pointer and decrement the bottom pointer till you hit middle of list

 

Loading...

Input

5 1 2 3 4 5

Expected Output

5 4 3 2 1