All submissions

Reverse an Array In-Place

Code

#include <stdio.h>

void reverse_array(int arr[], int n) {
    // Your logic here
    int low = 0, high = n-1;
    while(low < high)
    {
        int temp = arr[low];
        arr[low] = arr[high];
        arr[high] = temp;
        low++;
        high--;
    }
}

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

 

Solved with two pointers, one pointing to first element and another to the last element. iterating over array and swapping each first and last element until the middle element is reached

 

Loading...

Input

5 1 2 3 4 5

Expected Output

5 4 3 2 1