In this article, we will write a C program that reverses an array without using any other array.
Sample Examples:
Input: arr[] = {1, 2, 3, 4, 5};
Output: arr[] = {5, 4, 3, 2, 1};
Input: arr[] = {30, 10, 20, 15};
Output: arr[] = {15, 20, 10, 30};
The basic idea behind reversing an array without using any auxiliary array is to swap the elements of the first half of the array with the elements of the second half.
In other words, swap the first element of the array with the last element, swap the second element of the array with the second last element and so on until you reach the middle element.
See the implementation in the following C program:
// C program to reverse array elements // without using another array #include <stdio.h> int main(){ // Given array int arr[] = {1, 2, 3, 4, 5}; int length = sizeof(arr)/sizeof(arr[0]); int start = 0; int end = length - 1; // Print the original Array printf("Before Reversing: "); for(int i = 0; i < length; i++){ printf("%d ", arr[i]); } // Run loop until you reach middle element while(start < end){ // Swap element at index 'start' with element at index 'end' int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } printf("\nAfter Reversing: "); for(int i = 0; i < length; i++){ printf("%d ", arr[i]); } return 0; }
Output:
Before Reversing: 1 2 3 4 5 After Reversing: 5 4 3 2 1
Code Explanation:
- Declares an array of integers
arr
with 5 elements and assigns values to it. - Calculates the length of the array by dividing the total size of the array by the size of one element.
- Initializes two variables
start
andend
with 0 andlength-1
respectively. We subtract 1 from thelength
because the array index starts at 0. - Prints the original array using a for loop that iterates over each element of the array.
- Executes a while loop that runs until
start
is less thanend
. - Swaps the element at index
start
with the element at indexend
. - Increments
start
by1
and decrementsend
by1
in each iteration of the while loop. - Prints the reversed array using another for loop that iterates over each element of the array.
That’s all for this article. Thanks for reading!