C Program to Sort the Elements of an Array in Descending Order
Last Updated :
29 Jul, 2022
Here, we will sort the elements of an array in descending order using a C program.
Example:
Input:
array = [45, 22, 100, 66, 37]
Output:
[100, 66, 45, 37, 22]
Method 1:
The for loops iterate the array of elements and then the if statement compares the first element of an array with other all elements, the second element of an array with other elements, and so on, to print the descending order of an array.
C
#include <stdio.h>
int main()
{
int a[5] = { 45, 22, 100, 66, 37 };
int n = 5, i, j, t = 0;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (a[i] < a[j]) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
for (i = 0; i < n; i++) {
printf ( "%d " , a[i]);
}
return 0;
}
|
Method 2: Using functions
C
#include <stdio.h>
int desc_order( int a[10], int n)
{
int i, j, t = 0;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (a[i] < a[j]) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
for (i = 0; i < n; i++) {
printf ( "%d " , a[i]);
}
return 0;
}
int main()
{
int arr[5] = { 45, 22, 100, 66, 37 };
int num = 5;
desc_order(arr, num);
}
|
Share your thoughts in the comments
Please Login to comment...