C++ Program to Reverse Array with Output and Explanation
for (int i = 0; i < n / 2; i++) std::swap(arr[i], arr[n - i - 1]);.Examples
How to Think About It
Algorithm
Code
#include <iostream> using namespace std; int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); for (int i = 0; i < n / 2; i++) { swap(arr[i], arr[n - i - 1]); } for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; return 0; }
Dry Run
Let's trace the array {1, 2, 3, 4, 5} through the code to see how it reverses.
Initial array
arr = {1, 2, 3, 4, 5}, n = 5
First iteration (i=0)
Swap arr[0] and arr[4]: swap 1 and 5 -> arr = {5, 2, 3, 4, 1}
Second iteration (i=1)
Swap arr[1] and arr[3]: swap 2 and 4 -> arr = {5, 4, 3, 2, 1}
Loop ends
Middle element arr[2] = 3 stays the same
Print reversed array
Output: 5 4 3 2 1
| i | arr[i] | arr[n-i-1] | Array after swap |
|---|---|---|---|
| 0 | 1 | 5 | {5, 2, 3, 4, 1} |
| 1 | 2 | 4 | {5, 4, 3, 2, 1} |
Why This Works
Step 1: Swapping pairs
Swapping elements at positions i and n - i - 1 reverses the array by exchanging the first with the last, second with second last, and so on.
Step 2: Loop until middle
The loop runs only till the middle because after that, elements would be swapped back to original positions.
Step 3: In-place reversal
The reversal happens inside the original array without extra space, making it memory efficient.
Alternative Approaches
#include <iostream> using namespace std; int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); int temp[n]; for (int i = 0; i < n; i++) { temp[i] = arr[n - i - 1]; } for (int i = 0; i < n; i++) { arr[i] = temp[i]; } for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; return 0; }
#include <iostream> using namespace std; void reverseArray(int arr[], int start, int end) { if (start >= end) return; swap(arr[start], arr[end]); reverseArray(arr, start + 1, end - 1); } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); reverseArray(arr, 0, n - 1); for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs n/2 times, which is O(n), because each iteration swaps two elements.
Space Complexity
The reversal is done in-place using constant extra space O(1), no additional arrays needed.
Which Approach is Fastest?
The in-place swap method is fastest and most memory efficient compared to using a temporary array or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| In-place swap | O(n) | O(1) | Memory efficient and fast |
| Temporary array | O(n) | O(n) | Simple but uses extra memory |
| Recursion | O(n) | O(n) | Elegant but uses call stack memory |
std::swap to easily exchange two elements without extra variables.