Learn Programming and technology with ease @ developerpublish.com

HomeC++C++ Program to Calculate Standard Deviation

# C++ Program to Calculate Standard Deviation

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.

## Source 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.

1. 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}`
2. 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.
3. 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.Â
4. 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 function `variance=variance/5.`
5. Declare aÂ for loopÂ with the condition `(i = 0; i < 5; ++i)`Â and display the output statements using theÂ cout function.

Share:

### You May Also Like

#### C++ Program to Generate Multiplication Table

In this post, you will learn how to Generate Multiplication Table using C++ programming language. This lesson will teach you...
• C++
• January 30, 2022

#### C++ Program to Display Fibonacci Sequence

In this post, you will learn how to Display Fibonacci Sequence using C++ programming language. This lesson will teach you...
• C++
• January 30, 2022

#### C++ Program to Find GCD of two Numbers

In this post, you will learn how to Find GCD of two Numbers using C++ programming language. This lesson will...
• C++
• January 30, 2022