C Program to reverse an array.
Objective
Write a C program to reverse the contents of an array.
Algorithm / Approach
- Declare an original array
orig[5]and a destination arrayrev[5]. - Read elements into the original array.
- Use a
forloop with two counters:istarting at the end of the original array (4) and going down, andjstarting at the beginning of the reversed array (0) and going up. - Copy the elements:
rev[j] = orig[i]. - Print the reversed array.
main.c
#include<stdio.h>
int main( ) {
int i, j;
int orig[5], rev[5];
printf("Enter array elements : ");
for (i = 0; i < 5 ; i++){
scanf("%d", &orig[i]);
}
for (i=4, j=0; i>=0; i--,j++){
rev[j]=orig[i];
}
printf("Reverse array is : ");
for (i = 0; i < 5; i++){
printf("%d ", rev[i]);
}
return 0;
}
Expected Output
Enter the array elements : 1 2 3 4 5 Reverse array is : 5 4 3 2 1
Explanation of the Program
- Reversing an array using a secondary destination array is easy. You read from the back of the first array and write to the front of the second array.
- Note: You can also reverse an array "in-place" without using a second array by swapping the first element with the last, the second with the second-to-last, stopping when you reach the middle.
Complexity
Time Complexity
O(n)
Space Complexity
O(n) - Since we allocate a second array.