Calculating Standard Deviation in C++ Made Easy

Prerequisites

To follow along with this example, make sure you have a solid grasp of C++ fundamentals, including:

  • Arrays
  • For loops
  • Functions
  • While and do…while loops

The Problem: Calculating Standard Deviation

Standard deviation is a crucial concept in statistics, measuring the dispersion of a dataset from its mean value. But how do you calculate it efficiently?

Introducing the calculateSD() Function

To simplify the process, we’ll create a custom calculateSD() function that takes an array of 10 elements as input. This function will calculate the standard deviation and return the result to the main function.

How It Works

The calculateSD() function iterates through the array using a for loop, calculating the mean and variance of the dataset. Then, it returns the square root of the variance, which represents the standard deviation.


#include <cmath>

double calculateSD(double data[], int size) {
  double sum = 0.0;
  for (int i = 0; i < size; ++i) {
    sum += data[i];
  }
  double mean = sum / size;

  double sqDiffSum = 0.0;
  for (int i = 0; i < size; ++i) {
    sqDiffSum += (data[i] - mean) * (data[i] - mean);
  }
  double variance = sqDiffSum / size;

  return sqrt(variance);
}

Putting It All Together

Here’s an example program that demonstrates the power of the calculateSD() function:


int main() {
  double data[10] = {1.2, 2.3, 3.4, 4.5, 5.6, 6.7, 7.8, 8.9, 9.1, 10.2};
  int size = sizeof(data) / sizeof(data[0]);

  double standardDeviation = calculateSD(data, size);
  std::cout << "Standard Deviation: " << standardDeviation << std::endl;

  return 0;
}

Related Reading: Calculate Average of Numbers Using Arrays, a perfect complement to this standard deviation tutorial.

Leave a Reply