All submissions

Reverse an Array Using Only Pointers

Code

#include <stdio.h>

void reverse_array(int *ptr, int n) {
    int l = 0;
    int r = (n-1);

    while (l < r) {
        int tmp = *(ptr + r);
        *(ptr + r) = *(ptr + l);
        *(ptr + l) = tmp;
        l++;
        r--;
    }
}

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

Using two pointers. The left pointer  (l) is starting at the initial position of the array and the right pointer at the end of the array (n-1). The temporary variable holds at every cycle the value of the right most position and then the swap happens the left most position takes its value from the tmp variable and then the pointers are going to the middle until they match each other 

 

 

 

Loading...

Input

5 1 2 3 4 5

Expected Output

5 4 3 2 1