C Program to Reverse an Array with Output
for (int i = 0; i < n / 2; i++) { int temp = arr[i]; arr[i] = arr[n - 1 - i]; arr[n - 1 - i] = temp; }.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); for (int i = 0; i < n / 2; i++) { int temp = arr[i]; arr[i] = arr[n - 1 - i]; arr[n - 1 - i] = temp; } printf("Reversed array: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }
Dry Run
Let's trace reversing the array {1, 2, 3, 4, 5} through the code.
Initial array
arr = {1, 2, 3, 4, 5}, n = 5
First swap (i=0)
Swap arr[0] and arr[4]: arr = {5, 2, 3, 4, 1}
Second swap (i=1)
Swap arr[1] and arr[3]: arr = {5, 4, 3, 2, 1}
Loop ends at middle
No more swaps needed; arr is reversed.
| i | arr[i] | arr[n-1-i] | 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 elements
Swapping the element at position i with the element at position n-1-i moves the first element to the end and vice versa.
Step 2: Loop until middle
The loop runs only until the middle because after that, elements would be swapped back to original positions.
Step 3: In-place reversal
This method reverses the array without using extra memory, making it efficient.
Alternative Approaches
#include <stdio.h> int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); int rev[n]; for (int i = 0; i < n; i++) { rev[i] = arr[n - 1 - i]; } printf("Reversed array: "); for (int i = 0; i < n; i++) { printf("%d ", rev[i]); } return 0; }
#include <stdio.h> void reverse(int arr[], int start, int end) { if (start >= end) return; int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; reverse(arr, start + 1, end - 1); } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); reverse(arr, 0, n - 1); printf("Reversed array: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } 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 a temporary variable, so space complexity is O(1).
Which Approach is Fastest?
In-place swapping is fastest and uses least memory compared to using an auxiliary array or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| In-place swapping | O(n) | O(1) | Memory efficient and fast |
| Auxiliary array | O(n) | O(n) | Simple but uses extra memory |
| Recursion | O(n) | O(n) | Demonstrates recursion but uses call stack |