In this article, we will learn to write a C program to reverse an array. Reversing an array means changing the order of elements so that the first element becomes the last element and the second element becomes the second last element and so on.
Reverse an array
Algorithm
- Initialize two variables start = 0 as starting index and end = n-1 as the end index.
- Swap arr[start] and arr[end] till the start index is less than the end index.
- Update the start index as start + 1 and the end index as end – 1.
C Program to Reverse an Array
C
#include <stdio.h>
void rvereseArray( int arr[], int start, int end)
{
int temp;
while (start < end) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
void printArray( int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf ( "%d " , arr[i]);
printf ( "\n" );
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
printArray(arr, n);
rvereseArray(arr, 0, n - 1);
printf ( "Reversed array is \n" );
printArray(arr, n);
return 0;
}
|
Output
1 2 3 4 5 6
Reversed array is
6 5 4 3 2 1
Complexity Analysis
- Time complexity: O(n), where n is the number of elements in the array.
- Auxiliary space: O(1)
Refer to the complete article Write a program to reverse an array or string for more methods to reverse an array or string.
Related Articles
Last Updated :
31 Jul, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...