Home  >  Article  >  Backend Development  >  C program to find the median of a given list

C program to find the median of a given list

PHPz
PHPzforward
2023-09-14 13:21:08985browse

C program to find the median of a given list

If the elements in the list are arranged in order, the middle value that divides the elements in the list into two parts and has an equal number of elements on both sides is called the median.

There is only one intermediate value for an odd number of elements; and there are two intermediate values ​​for an even number of items.

Thus, the median of an even number of items is specified as the average of the two middle values.

Algorithm

Please refer to the algorithm given below to calculate the median.

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

Step 2 - Sort the items in ascending order.

Step 3 - Calculate the median.

The logic for sorting numbers before finding the 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 for finding the median of a 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

The following is a C program to calculate the median of a given number -

Live Demonstration

#include<stdio.h>
#define N 10
main( ){
   int i,j,n;
   float median,a[N],t;
   printf("Enter the number of items</p><p>");
   scanf("%d", &n);
   /* Reading items into array a */
   printf("Input %d values </p><p>",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("</p><p></p><p>Median is %f</p><p>", median);
}

Output

When the above program is executed, the following output is produced-

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

The above is the detailed content of C program to find the median of a given list. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete