#include <stdio.h> void reverse_array(int arr[], int n) { // Your logic here volatile int i = 0, j = n-1; while(i<j){ arr[i] = arr[i] + arr[j]; arr[j] = arr[i] - arr[j]; arr[i] = arr[i] - arr[j]; i++;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; }
Use a two pointer approach, swap leftmost current index with rightmost current index.
For simplicity arr[i] = a, arr[j] = b
Swap:
add both a+b and store into a
subtract b from a to get the original value of a and store it in b
subtract b from a to get the original value of b and store it in a
Test Cases
Test Results
Input
5 1 2 3 4 5
Expected Output
5 4 3 2 1