Open In App

C Program to Sort the Elements of an Array in Descending Order

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 program to sort array elements in descending order
  
#include <stdio.h>
  
int main()
{
  
    int a[5] = { 45, 22, 100, 66, 37 };
    int n = 5, i, j, t = 0;
    
    // iterates the array elements
    for (i = 0; i < n; i++) {
        
        // iterates the array elements from index 1
        for (j = i + 1; j < n; j++) {
            
            // comparing the array elements, to set array
            // elements in descending order
            if (a[i] < a[j]) {
                t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
        }
    }
    // printing the output
    for (i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    return 0;
}

Output
100 66 45 37 22 

Method 2: Using functions




// C program to sort array elements in descending order
// using functions
  
#include <stdio.h>
// defining the function
int desc_order(int a[10], int n)
{
    int i, j, t = 0;
    
    // iterates the array elements
    for (i = 0; i < n; i++) {
        
        // iterates the array elements from index 1
        for (j = i + 1; j < n; j++) {
            
            // comparing the array elements, to set array
            // elements in descending order
            if (a[i] < a[j]) {
                t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
        }
    }
    // printing the output
    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;
    
    // calling the function
    desc_order(arr, num);
}

Output
100 66 45 37 22 

Article Tags :