C program to calculate the standard deviation

CServer Side ProgrammingProgramming

Standard deviation is used to measure deviation of data from its mean. The mathematical formula to calculate the standard deviation is as follows −

$$s=\sqrt{Variance}$$

where

Variance$$=\frac{1}{n}\:\:\displaystyle\sum\limits_{i=1}^n (x_{i}-m)^{2}$$

and

$$m=mean=\frac{1}{n}\:\displaystyle\sum\limits_{i=1}^n x_{i}$$


Algorithm

Refer an algorithm given below to calculate the standard deviation for the given numbers.

Step 1 − Read n items.

Step 2 − Calculate sum and mean of the items.

Step 3 − Calculate variance.

Step 4 − Calculate standard deviation.

The logic used in the program for calculating standard deviation is as follows −

for (i = 1 ; i<= n; i++){
   deviation = value[i] - mean;
   sumsqr += deviation * deviation;
}
variance = sumsqr/(float)n ;
stddeviation = sqrt(variance) ;

Example

Following is the C program to calculate the standard deviation for the given numbers −

#include <math.h>
#define MAXSIZE 100
main( ) {
   int i,n;
   float value [MAXSIZE], deviation,
   sum,sumsqr,mean,variance,stddeviation;
   sum = sumsqr = n = 0 ;
   printf("Input values: input -1 to end \n");
   for (i=1; i< MAXSIZE ; i++) {
      scanf("%f", &value[i]);
      if (value[i] == -1)
      break;
      sum += value[i];
      n += 1;
   }
   mean = sum/(float)n;
   for (i = 1 ; i<= n; i++) {
      deviation = value[i] - mean;
      sumsqr += deviation * deviation;
   }
   variance = sumsqr/(float)n ;
   stddeviation = sqrt(variance) ;
   printf("\nNumber of items : %d\n",n);
   printf("Mean : %f\n", mean);
   printf("Standard deviation : %f\n", stddeviation);
}

Output

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

Input values: input -1 to end
2 4 6 8 12 4.5 6.7 0.3 2.4 -1
Number of items: 9
Mean: 5.100000
Standard deviation: 3.348300
raja
Published on 25-Mar-2021 11:41:52
Advertisements