C Program to Sort Array in Descending Order


Question: Write a program in C to read an array containing n elements and sort this array in descending order.

Program


#include<stdio.h>

int main()
{
 float a[100], temp;
 int i, j, n;

 printf("Enter n:");
 scanf("%d", &n);
 
 /* Reading Array */
 printf("Enter numbers:\n");
 for(i=0;i< n;i++)
 {
  printf("a[%d]=",i);
  scanf("%f",&a[i]);
 }
 /* Sorting array in descending order */
 for(i=0;i< n-1;i++)
 {
  for(j=i+1;j< n;j++)
  {
   if(a[i]< a[j])
   {
    temp = a[i];
    a[i] = a[j];
    a[j] = temp;
   }
  }
 }
 /* Displaying result */
 printf("Array in descending order is:\n");
 for(i=0;i< n;i++)
 {
  printf("%0.1f\t", a[i]);
 }

 return(0);
}

Output

Enter n: 4↲
Enter numbers:
a[0] = 21↲
a[1] = 11↲
a[2] = -13↲
a[3] = 12↲
Array in descending order is:
21.0    12.0    11.0    -13.0