Open In App

Standard Deviation in C

Last Updated : 06 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Standard deviation is a statistical metric generally used to understand the distribution in a dataset. In this article, we will learn to write a C program to calculate the Standard deviation.

What is the Standard Deviation?

The standard deviation of given data is the extent to which the individual data items differ from the mean of the given data. Mathematically,

\sigma = \sqrt\frac{\sum{(X-\mu)^2}}{N}

where,

  • σ = standard deviation.
  • X = individual data element.
  • μ = mean of given data.
  • N = number of data items.

C Program to Find Standard Deviation

C




// C program to find standard deviation of the given data
// items
#include <math.h>
#include <stdio.h>
 
void calculateStandardDeviation(int N, float data[])
{
    // variable to store sum of the given data
    float sum = 0;
    for (int i = 0; i < N; i++) {
        sum += data[i];
    }
 
    // calculating mean
    float mean = sum / N;
 
    // temporary variable to store the summation of square
    // of difference between individual data items and mean
    float values = 0;
 
    for (int i = 0; i < N; i++) {
        values += pow(data[i] - mean, 2);
    }
 
    // variance is the square of standard deviation
    float variance = values / N;
 
    // calculating standard deviation by finding square root
    // of variance
    float standardDeviation = sqrt(variance);
 
    // printing standard deviation
    printf("%.2f\n", standardDeviation);
}
 
int main()
{
    int size = 6;
    float data[] = { 94, 93.4, 89, 88, 95, 96.7 };
 
    printf("For the given data items: \n");
    for (int i = 0; i < size; i++) {
        printf("%.2f  ", data[i]);
    }
    printf("\n\n");
    printf("Standard Deviation is: \n");
    calculateStandardDeviation(size, data);
    return 0;
}


Output

For the given data items: 
94.00 93.40 89.00 88.00 95.00 96.70
Standard Deviation is:
3.14

Complexity Analysis

  • Time Complexity: O(n), where n is the size of input data.
  • Space Complexity: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads