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.

How to Calculate Standard Deviation?

RUN CODE SNIPPET

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:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this post, you will learn how to Generate Multiplication Table using C++ programming language. This lesson will teach you...
  • C++
  • January 30, 2022
In this post, you will learn how to Display Fibonacci Sequence using C++ programming language. This lesson will teach you...
  • C++
  • January 30, 2022
In this post, you will learn how to Find GCD of two Numbers using C++ programming language. This lesson will...
  • C++
  • January 30, 2022