Summary: In this programming example, we will learn to reverse an array without using another array in C.
The logic of reversing an array without using another array is to swap elements of the first half with elements of the second half i.e. the first element with the last element, then the second element with the second last element, and so on, till the middle element of the array.
In programming, we use while loop with the condition i<j
to implement the process described above. Because if i==j
, it means it is the middle element of the array and the middle element doesn’t need to be swapped.
Steps to reverse an array without using another array in C:
- Initialize an array with values.
- Set
i=0
to point to the first element andj=length-1
to point to the last element of the array. - Run while loop with the condition
i<j
.- Inside loop swap ith and jth element in the array.
- Increment
i
and decrementj
.
- End Loop.
- Display the array and end program.
Here is the implementation of the steps in C:
#include<stdio.h>
//function to display array
void display(int array[], int length){
for(int i=0; i<length; i++){
printf("%d ",array[i]);
}
printf("\n");
}
int main(){
/*
*You can take input in array using loop and scanf
*Here for simplicity, I have pre-initialized array
*/
int array[] = {1, 2, 3, 4, 5};
int temp, length = 5;
int i=0; //for pointing 1st element of the array
int j=length-1; //for pointing last element of the array
//display original array
printf("Original array: ");
display(array, length);
while(i<j){
//swap
temp = array[i];
array[i] = array[j];
array[j] = temp;
//update i and j
i++;
j--;
}
//display reversed array
printf("Reverse of array: ");
display(array, length);
return 0;
}
Output:
The above program reverses an array (in-place) with a time complexity equal to O(n).
This is one of the methods using which we can reverse an array in the C programming language. Comment if you have any other suggestions.