Software & Finance





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





I have given the simple C program for calculating sample and population variance 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 CalculateMean(float *value, int max)

{

    int i;

    float sum = 0;

 

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

        sum = sum + value[i];

    return (sum / max);

}

 

 

 

float CalculateVariane(float *value, int max)

{

    float mean = CalculateMean(value, max);

    int i = 0;

    float temp = 0;

 

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

         temp += (value[i] - mean) * (value[i] - mean) ;

 

    return temp / max;

}

 

float CalculateSampleVariane(float *value, int max)

{

    float mean = CalculateMean(value, max);

    float temp = 0;

    int i = 0;

 

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

         temp += (value[i] - mean) * (value[i] - mean) ;

 

    return temp / (max - 1);

}

 

 

int main()

{

 

    float arrNumbers[100];

    int i, max;

    float mean;

    char buf[1024];

    float variance, samplevariance;

 

 

    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("\nTotal Numbers: %d", max);

 

    mean = CalculateMean(arrNumbers, max);

    variance = CalculateVariane(arrNumbers, max);

    samplevariance = CalculateSampleVariane(arrNumbers, max);

 

    printf("\nMean: %f", mean);

    printf("\nSample Variance: %f", samplevariance);

    printf("\nPopulation Variance: %f",  variance);

 

 

    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

 

Mean: 5.500000

 

Sample Variance: 6.055555 

Population Variance: 5.450000