All submissions

Reverse an Array Using Only Pointers

Code

#include <stdio.h>

void reverse_array(int *ptr, int n) {
    // Your logic here
    for(int i=0,j=n-1;i<j;i++,j--){     // intilize i and j ,and iterate the loop i<j times 
        int temp = *(ptr+i);            // storing *(ptr+i) in temp
        *(ptr+i) = *(ptr+j);            // stroing *(ptr+j) in *(ptr+i)
        *(ptr+j) = temp;                // storing temp in *(ptr+j)
    }
}

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

void reverse_array(int *ptr, int n) {
    // Your logic here
    for(int i=0,j=n-1;i<j;i++,j--){     // intilize i and j ,and iterate the loop i<j times 
        int temp = *(ptr+i);            // storing *(ptr+i) in temp
        *(ptr+i) = *(ptr+j);            // stroing *(ptr+j) in *(ptr+i)
        *(ptr+j) = temp;                // storing temp in *(ptr+j)
    }
}

 

 

Loading...

Input

5 1 2 3 4 5

Expected Output

5 4 3 2 1