Open In App

Find the Standard Deviation of Array Elements in C++

Last Updated : 02 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In statistical analysis, the standard deviation is a quantity that measures how much the data points are spread over the dataset. It indicates how much the single data points deviate from the mean (average) of the dataset. In this article, we look at how to find the standard deviation of the numeric elements of the Array in C++.

For Example,

Input:
myArray = { 5, 10, 15, 20, 25, 30, 35, 40,
45, 50, 55, 60, 65, 70, 75 }
Output:
Standard_Deviation = 21.6025

Calculate Standard Deviation of Numbers in an Array in C++

To calculate the standard deviation, we first need to calculate the mean and variance of the dataset. The formula for mean, variance, and standard deviation is as follows:

Mean (Average)

{\displaystyle A={\frac {1}{n}}\sum _{i=1}^{n}a_{i}={\frac {a_{1}+a_{2}+\cdots +a_{n}}{n}}}

Variance

\sigma^{2}=V(X)=E[(X-\mu)^2]=\sum P_{i}(x_{i} -\mu)^2

Standard Deviation

\sigma=\sqrt{\sum_{i} P_{i}(x_{i} - \mu)^2}

C++ Program to Find the Standard Deviation of Array Elements

C++

// C++ Program to Calculate Standard Deviation of a Vector
// of Integers
  
#include <cmath>
#include <iostream>
#include <vector>
  
using namespace std;
  
// Function to calculate the standard deviation of a vector
// of integers
double calculateStandardDeviation(const vector<int>& arr)
{
    double sum = 0.0, mean, standardDeviation = 0.0;
  
    int size = arr.size();
  
    // Calculate the sum of elements in the vector
    for (int i = 0; i < size; ++i) {
        sum += arr[i];
    }
  
    // Calculate the mean
    mean = sum / size;
  
    // Calculate the sum of squared differences from the
    // mean
    for (int i = 0; i < size; ++i) {
        standardDeviation += pow(arr[i] - mean, 2);
    }
  
    // Calculate the square root of the variance to get the
    // standard deviation
    return sqrt(standardDeviation / size);
}
  
int main()
{
    // Sample vector of integers
    vector<int> arr = { 5,  10, 15, 20, 25, 30, 35, 40,
                        45, 50, 55, 60, 65, 70, 75 };
  
    // Display the calculated standard deviation
    cout << "Standard Deviation = "
         << calculateStandardDeviation(arr) << endl;
  
    return 0;
}

                    

Output
Standard Deviation = 21.6025

Time Complexity: O(n) – where ‘n’ is the number of elements in the array.
Space Complexity: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads