In this post, you will learn how to Calculate Standard Deviation using C++ programming language.
This lesson will teach you how to Calculate Standard Deviation, using mathematical operators, assignment operator and the for loop statement using the C++ Language. Let’s look at the below source code.
How to Calculate Standard Deviation?
RUN CODE SNIPPETSource Code
#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
The statements #include<iostream>, using namespace std, #include<cmath>, int main are the main factors that support the function of the source code.
Now we can look into the working and layout of the code’s function.
- Initialize the variable val as float value and a an array with the symbol [ ] and assign the values to be calculated
{12.5, 7.0, 10.0, 7.8, 15.5}
- Initialize the string values sum, mean, variance, stdDeviation as float values and assign the variable sum and variance as 0.0. And the variable i as an integer.
- Declare a for loop with the condition
(i = 0; i < 5; ++i)
, and in the body of the for loop include two mathematical functions to find the value of sum and mean. - Declare a for loop with the condition
(i = 0; i < 5; ++i)
, and in the body of the loop include mathematical functions to find the value of variance and stdDeviation. Using the assignment operator perform the following functionvariance=variance/5.
- Declare a for loop with the condition
(i = 0; i < 5; ++i)
and display the output statements using the cout function.