Software & Finance





C Programming (Turbo C++ Compiler) - Calculate Median





I have given the simple C program for calculating median for a set of numbers. The other related linkes are,

Calculate Mean

Calculate Median

Calculate Mode

Calculate Range

Calculate Variance

Calculate Standard Deviation


Source Code


#include <stdlib.h>

#include <stdio.h>

#include <math.h>

 

 

 

float CalculateMedian(float *arrValue, int max)

{

    float median = 0;

    float value[100];

    int i, j;

    float temp;

    if(max > 100)

        return 0;

    for(i = 0; i < max; i++)

        value[i] = arrValue[i];

    for(i = 0; i < max; i++)

    {           

        for(j = 0; j < max - i - 1; j++)

        {

                if(value[j] > value[j + 1])

                {

                    temp = value[j];

                    value[j] = value[j + 1];

                    value[j + 1] = temp;

                }

        }

    }

    if( (max % 2) == 1)

    {

        median =  value[ (max + 1) / 2 - 1];

    }

    else

    {

        median = (value[max / 2] + value[max / 2 - 1]) / 2;

    }

    return median;

}

 

 

 

int main()

{

    float arrNumbers[100];

    int i, max;

    float median;

    char buf[1024];

 

    printf("Total Number of Elements: ");

    scanf("%d", &max);

 

    for(i = 0; i < max; i++)

    {

       printf("Enter [%d] Number: ", i + 1);

       scanf("%f", &arrNumbers[i]);

    }

 

    printf("Total Numbers: %d\n", max);

 

    median = CalculateMedian(arrNumbers, max);

 

    printf("Median: %f", median);

       

    return 0;

}

 

 

Output


Total Number of Elements: 10

Enter [1] Number: 6

Enter [2] Number: 7

Enter [3] Number: 8

Enter [4] Number: 7

Enter [5] Number: 6

Enter [6] Number: 5

Enter [7] Number: 2

Enter [8] Number: 2

Enter [9] Number: 9

Enter [10] Number: 3

 

Total Numbers: 10

 

Median: 6.000000