Reverse an Array In-Place

Code

// You are given an array of integers and its length.
// Write a function to reverse the array in-place, without using another array.
#include <stdio.h>

void reverse_array(int *arr, int n){
    int l = 0, r = n - 1 - l; 
    int tmp = 0;
    while(l<=r){
        tmp = arr[r];
        arr[r] = arr[l]; 
        arr[l] = tmp; 
        l++;
        r--; 
    }
}

int main(){
    int n, arr[100];
    scanf("%d",&n);
    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]);
    }
    return 0;
} 

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5 1 2 3 4 5

Expected Output

5 4 3 2 1