Reversing an array means the swapping last element and first element, second last element and second element, and so on. In this article, we will learn how to reverse an array in C.
The simplest method to reverse an array in C program is by using two pointers: one starting at the beginning (left) and one at the end (right) of the string. Swap the elements at these pointers while moving them towards centre of the array until the pointers meet.
#include <stdio.h>
void rev(int arr[], int n) {
// Two pointers
int l = 0, r = n - 1;
while (l < r) {
// Swap the elements
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
// Move pointers towards middle
l++;
r--;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
// Reverse array arr
rev(arr, n);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output
5 4 3 2 1
Apart from the above method, an array can also be reversed using the methods shown below:
Table of Content
Using Recursion
This method is the recursive implementation of two pointer approach but uses recursive call to swap the elements and move the two pointers.
#include <stdio.h>
void rev(int arr[], int l, int r) {
if (l >= r) {
return;
}
// Swap the elements
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
// Recursively call function to reverse the
// remaining part
rev(arr, l + 1, r - 1);
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
// Reverse the array arr
rev(arr, 0, n - 1);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output
5 4 3 2 1
Using Temporary Array
Another method is to create a new array to store the reversed elements by copying the array from last to first, then copy the contents back into the original array.
#include <stdio.h>
void rev(int arr[], int n) {
int temp[n];
// Store elements into temp in reverse order
for (int i = 0; i < n; i++) {
temp[i] = arr[n - 1 - i];
}
// Copy reversed array back to original array
for (int i = 0; i < n; i++) {
arr[i] = temp[i];
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
// Reverse the array arr
rev(arr, n);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output
5 4 3 2 1