In this article, we are going to learn how to reverse arrays element-wise in C language. We will take an arrays and then we will reverse its elements one by one and will display the fully reversed array.
C Program to Reverse an array
In this example, we are going to make use of a single array to reverse its elements. We will not use another array.
We will ask the user to decide the length of the array and then the user will enter the elements of the array.
- If the length of the array, entered by user is even then all elements of the array must swap with a relative element.
- If the length of the array, entered by user is odd then the element at the center position will remain the same.
//how to Reverse Array in C
#include <stdio.h>
int main()
{
int arr[10], num ;
printf("Please enter the Size of array with Max size 10: ");
scanf("%d",&num);
printf("Please enter the elements in this Array: ");
for(int i=0; i < num; i++)
scanf("%d",&arr[i]);
int i = 0;
int j = num-1;
int temp;
while(i <= num/2)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
printf("\nThe Reverse of array entered by you is: \n");
for (int i = 0; i < num; ++i)
{
printf("%d ", arr[i]);
}
return 0;
}
Output
Please enter the Size of array with Max size 10: 5
Please enter the elements in this Array: 3 15 8 9 6 21
The Reverse of array entered by you is:
21 6 9 15 3