In this tutorial you will learn about the C++ Program to Calculate Standard Deviation and its application with practical example.
In this tutorial, we will learn to create a c++ Program to Calculate Standard Deviation.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- C++ Operators.
- Functions.
- For Loop and while loop.
- Array.
- String.
What Is Standard Deviation.?
The concept behind Standard Deviation is a measure of how spread out numbers are in a given Scenario.In Mathematical term, the Standard Deviation is measure of the amount of variation on set of values.
formula is Standard deviation is :=>
where ∑ sum means “sum of”.
x is a value in the data set.
μ is the mean of the data set.
and N is the number of data points.
in simple form Standard deviation is .
C++ Program to Calculate Standard Deviation
In this program , we will calculate Standard Deviation of a given numbers .First of all user will be prompted to enter a number and afterword passing these value to function to calculate Standard deviation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include <iostream> #include <cmath> using namespace std; float SD(float values[]) // function for calculating standadr deviation { float sum = 0.0, mean, sd = 0.0; int i; for(i = 0; i < 10; ++i) { sum = sum + values[i]; // calculating sum } mean = sum/10; // finding mean. for(i = 0; i < 10; ++i) sd = sd + pow(values[i] - mean, 2); // calculating standard deviation return sqrt(sd / 10); } int main() { int i; float arr[10]; cout << "Enter 10 elements: "; for(i = 0; i < 10; ++i) cin >> arr[i]; cout << endl << "Standard Deviation = " << SD(arr); // calling function return 0; } |
Output
In the above program, we have first declared and initialized a set variables required in the program.
- arr[] = it will hold entered elements.
- value = it will hold a elements values.
- i= for iteration.
- sum= add all elements to find mean.
- mean=hold the mean value.
- sd= gives us standard deviation.
Now let us look method to find standard deviation step by step.
- first or all take elements from user.
- then pass these elements to function SD.
- where first we calculate the mean (average) of each data set.
- then,subtracting the mean from each number.
- then,Square each deviation.
- after that add all the squared deviations.
- Divide the value obtained by the number of items in the data set.
- Calculate the square root of the value obtained (Variance).
- And at the return the sd to main function were we print standard deviation.