C++ Program to Calculate Standard Deviation

C++ProgrammingServer Side Programming

Standard deviation is the measure of how spread out the numbers in the data are. It is the square root of variance, where variance is the average of squared differences from the mean.

A program to calculate the standard deviation is given as follows.

Example

 Live Demo

#include <iostream>
#include <cmath>
using namespace std;
int main() {
   float val[5] = {12.5, 7.0, 10.0, 7.8, 15.5};
   float sum = 0.0, mean, variance = 0.0, stdDeviation;
   int i;
   for(i = 0; i < 5; ++i)
   sum += val[i];
   mean = sum/5;
   for(i = 0; i < 5; ++i)
   variance += pow(val[i] - mean, 2);
   variance=variance/5;
   stdDeviation = sqrt(variance);
   cout<<"The data values are: ";
   for(i = 0; i < 5; ++i)
   cout<< val[i] <<" ";
   cout<<endl;
   cout<<"The standard deviation of these data values is "<<stdDeviation;
}

Output

The data values are: 12.5 7 10 7.8 15.5
The standard deviation of these data values is 3.1232

In the above program, first the sum of the data values is obtained. Then the mean is found by dividing the sum by the number of elements. This is given in the following code snippet.

for(i = 0; i < 5; ++i)
sum += val[i];
mean = sum/5;

The variance of the data is found by squaring the differences from the mean, adding them and then finding their average. This is shown in the following code snippet.

for(i = 0; i < 5; ++i)
variance += pow(val[i] - mean, 2);
variance=variance/5;

The standard deviation is found by obtaining the square root of the variance. Then all the data values and the standard deviation is displayed. This is given as follows.

stdDeviation = sqrt(variance);
cout<<"The data values are: ";
for(i = 0; i < 5; ++i)
cout<< val[i] <<" ";
cout<<endl;
cout<<"The standard deviation of these data values is "<<stdDeviation;
raja
Published on 05-Oct-2018 11:44:30
Advertisements