All submissions

Reverse an Array Using Only Pointers

 

#include <stdio.h>

void reverse_array(int *ptr, int n) {
    // Your logic here
    int *start = ptr;       //index of first element ptr
    int *end = ptr + n - 1; //index of last element ptr

    //swap the element ptr from both the ends pointing towards the center
    while (start < end) 
    {
        int temp = *start;
        *start = *end;
        *end = temp;
        // move ptr inwards
        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;
}

 

 

 

 

Loading...

Input

5 1 2 3 4 5

Expected Output

5 4 3 2 1