Find the Standard Deviation of Array Elements in C++
Last Updated :
02 Feb, 2024
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)
Variance
Standard Deviation
C++ Program to Find the Standard Deviation of Array Elements
C++
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
double calculateStandardDeviation( const vector< int >& arr)
{
double sum = 0.0, mean, standardDeviation = 0.0;
int size = arr.size();
for ( int i = 0; i < size; ++i) {
sum += arr[i];
}
mean = sum / size;
for ( int i = 0; i < size; ++i) {
standardDeviation += pow (arr[i] - mean, 2);
}
return sqrt (standardDeviation / size);
}
int main()
{
vector< int > arr = { 5, 10, 15, 20, 25, 30, 35, 40,
45, 50, 55, 60, 65, 70, 75 };
cout << "Standard Deviation = "
<< calculateStandardDeviation(arr) << endl;
return 0;
}
|
OutputStandard Deviation = 21.6025
Time Complexity: O(n) – where ‘n’ is the number of elements in the array.
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...