In this tutorial, we will learn C Program to Reverse an Array element. Before continuing, you should have knowledge of the following topics in C programming.
Revering an array element: The entered array of integers will be reversed and displayed. Example:
Input:
arr = {1, 2, 3, 4, 5, 6}
Output:
Reversed arr: {6, 5, 4, 3, 2, 1}
Here, we will look at two different programs to Reverse an Array element in C.
- By standard method
- By creating a function and swapping.
C Program to print the elements of an array in reverse order
#include <stdio.h>
int main()
{
//Initialize array
int arr[50], size, i;
printf("Enter the size for an array: ");
scanf("%d", &size);
printf("Enter %d elements of an array:\n", size);
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
printf("Original order of an Array:\n");
for (i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\nReversed order of an array:\n");
for (i = size - 1; i >= 0; i--)
{
printf("%d ", arr[i]);
}
return 0;
}
Output:
Enter the size for an array: 5
Enter 5 elements of an array:
10
20
30
40
50
Original order of an Array:
10 20 30 40 50
Reversed order of an array:
50 40 30 20 10
C Program to to Reverse the Array Elements using Function
This program has a separate function(rev_Array()) to reverse the element in an array. The reversing of elements is done by swapping array elements.
#include <stdio.h>
void rev_Array(int arr[], int size)
{
int temp, i = 0;
//swapping
while (i < size)
{
temp = arr[i];
arr[i] = arr[size];
arr[size] = temp;
i++;
size--;
}
}
int main()
{
//Variables
int arr[50], size, i;
//user inputs
printf("Enter the size for an array: ");
scanf("%d", &size);
printf("Enter %d elements of an array:\n", size);
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
printf("Original order of an Array:\n");
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
//calling reverse function
rev_Array(arr, size - 1);
//printing the reversed order
printf("\nReversed order of an Array:\n");
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
return 0;
}
Output:
Enter the size for an array: 5
Enter 5 elements of an array:
20
30
40
60
80
Original order of an Array:
20 30 40 60 80
Reversed order of an Array:
80 60 40 30 20