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 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 Check Armstrong Number using C++ programming language. This lesson will teach you...
  • C++
  • December 2, 2024
In this post, you will learn how to Calculate the Sum of Natural Numbers using C++. This lesson will teach...
  • C++
  • December 2, 2024
In this post, you’ll learn how to write a Program to Add Two Integers in C++. This lesson will help...
  • C++
  • November 30, 2024