Exercise:
Write a C Program to calculate standard deviation.
Click Here to View the Solution!
#include <math.h>
#include <stdio.h>
float StandardDeviation(float data[]);
int main() {
int i;
float data[10];
printf("Enter 10 elements: ");
for (int i = 0; i < 10; ++i) {
scanf("%f", &data[i]);
printf("\nStandard Deviation = %.6f", StandardDeviation(data));
}
return 0;
}
float StandardDeviation(float data[]) {
float sum = 0.0, mean, SD = 0.0;
for (int i = 0; i < 10; ++i) {
sum += data[i];
}
mean = sum / 10;
for (int i = 0; i < 10; ++i) {
SD += pow(data[i] - mean, 2);
}
return sqrt(SD / 10);
}
Click Here to View the Output!
Enter 10 elements: 2 3 4 8 6 4 3 9 1 3
Standard Deviation = 2.451530
Click Here to View the Explanation!
- This program is used to calculates the standard deviation.
- A user-defined
function StandardDeviation
is declared that takes an array an its argument. - In
main()
, the program requests the user to enter 10 elements by using afor loop
which iterates 10 times and each time the user enters a number. All the numbers are stored in anarray data[i]
using thescanf() function
. - Initially, the
StandardDeviation function
is called from main with the entered parameter. - The
StandardDeviation function
is then initialized using afor loop
which iterates betweeni = 0
andi < 10.
In each iteration,i
is stored indata[i]
and added to the variablesum
. - The Standard Deviation is calculated by using the mean of the numbers thus, sum is divided by 10 and stored in
mean
. - A final
for loop
is initialized that will again iterate 10 times and each time execute the formulapow(data[i] – mean, 2)
and the results are consistently stored in the variableSD
. - Finally, the square root of
SD/10
is calculated and returned to main for printing.