Calculate Standard Deviation in C

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 a for loop which iterates 10 times and each time the user enters a number. All the numbers are stored in an array data[i] using the scanf() function.
  • Initially, the StandardDeviation function is called from main with the entered parameter.
  • The StandardDeviation function is then initialized using a for loop which iterates between i = 0 and i < 10. In each iteration, i is stored in data[i] and added to the variable sum.
  • 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 formula pow(data[i] – mean, 2) and the results are consistently stored in the variable SD.
  • Finally, the square root of SD/10 is calculated and returned to main for printing.