C Program to Sort an Array in Ascending or Descending Based on Even Count


Question: Write a program in C to read an array containing n integer numbers then sort this array into ascending order if it has more number of even numbers otherwise sort in descending order.

C Program


#include<stdio.h>


int main()
{
 int a[100], temp, i, j, n, ecount=0, ocount=0;

 /* Reading array */
 printf("Enter n:\n");
 scanf("%d", &n);
 printf("Enter numbers:\n");
 for(i=0;i< n;i++)
 {
  printf("a[%d]=",i);
  scanf("%d", &a[i]);
 }
 /* Counting odd and even */
 for(i=0;i< n;i++)
 {
  a[i]%2==0?ecount++:ocount++;
 }
 /* sorting */
 if(ecount>ocount)
 {
  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;
    }
   }
  }
 }
 else
 {
  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("Final array is:\n");
 for(i=0;i< n;i++)
 {
  printf("%d\t",a[i]);
 }
 
 return 0;
}