Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to calculate the standard deviation
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}$$
Syntax
#include <math.h> double sqrt(double x);
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 −
Note: Since this program requires interactive input, use predefined values for online execution.
#include <stdio.h>
#include <math.h>
int main() {
int i, n = 9;
float value[] = {2, 4, 6, 8, 12, 4.5, 6.7, 0.3, 2.4};
float deviation, sum, sumsqr, mean, variance, stddeviation;
sum = sumsqr = 0;
// Calculate sum
for (i = 0; i < n; i++) {
sum += value[i];
}
// Calculate mean
mean = sum / (float)n;
// Calculate sum of squared deviations
for (i = 0; i < n; i++) {
deviation = value[i] - mean;
sumsqr += deviation * deviation;
}
// Calculate variance and standard deviation
variance = sumsqr / (float)n;
stddeviation = sqrt(variance);
printf("Number of items: %d<br>", n);
printf("Mean: %.6f<br>", mean);
printf("Variance: %.6f<br>", variance);
printf("Standard deviation: %.6f<br>", stddeviation);
return 0;
}
Output
Number of items: 9 Mean: 5.100000 Variance: 11.210000 Standard deviation: 3.348300
Key Points
- Include
<math.h>header for thesqrt()function. - Standard deviation is the square root of variance.
- Use proper array indexing starting from 0 to avoid undefined behavior.
- Cast to
floatwhen dividing integers to get precise decimal results.
Conclusion
Standard deviation calculation in C involves computing the mean, finding squared deviations, calculating variance, and taking the square root. This statistical measure helps understand data spread and variability.
