C program to find the median of a given list.


If the elements of the list are arranged in order, then, the middle value which divides the items into two parts with equal number of items on either side is called the median.

Odd numbers of items have just one middle value whereas; even numbers of items have two middle values.

The median for even number of items is therefore, designated as the average of the two middle values.

Algorithm

Refer an algorithm given below to calculate the median.

Step 1 − Read the items into an array while keeping a count of the items.

Step 2 − Sort the items in increasing order.

Step 3 − Compute median.

The logic used to sort the numbers before finding a median is as follows −

for (i = 1 ; i <= n-1 ; i++){
   for (j = 1 ; j <= n-i ; j++){
      if (a[j] <= a[j+1]){
         t = a[j];
         a[j] = a[j+1];
         a[j+1] = t;
      } else
      continue ;
   }
}

The logic used to find a median of list is as follows −

if ( n % 2 == 0)
   median = (a[n/2] + a[n/2+1])/2.0 ;
else
   median = a[n/2 + 1];

Example

Following is the C program to calculate the median of given numbers −

 Live Demo

#include<stdio.h>
#define N 10
main( ){
   int i,j,n;
   float median,a[N],t;
   printf("Enter the number of items
");    scanf("%d", &n);    /* Reading items into array a */    printf("Input %d values
",n);    for (i = 1; i <= n ; i++)    scanf("%f", &a[i]);    /* Sorting begins */    for (i = 1 ; i <= n-1 ; i++){ /* Trip-i begins */       for (j = 1 ; j <= n-i ; j++) {          if (a[j] <= a[j+1]) { /* Interchanging values */             t = a[j];             a[j] = a[j+1];             a[j+1] = t;          }          else          continue ;       }    } /* sorting ends */    /* calculation of median */    if ( n % 2 == 0)       median = (a[n/2] + a[n/2+1])/2.0 ;    else    median = a[n/2 + 1];    /* Printing */    for (i = 1 ; i <= n ; i++)    printf("%f ", a[i]);    printf("

Median is %f
", median); }

Output

When the above program is executed, it produces the following output −

Enter the number of items
5
Input 5 values
2.3
1.2
3.8
4.6
8.9
8.900000 4.600000 3.800000 2.300000 1.200000

Median is 3.800000

Updated on: 25-Mar-2021

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements