
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Calculate Standard Deviation
Standard deviation is a measure of how spread out the numbers in a dataset are. It is the square root of the variance, where variance is the average of the squared differences from the mean. In this article, we will show you how to calculate the standard deviation in C++.

Let's understand this with an example:
Input: Numbers are 4, 8, 6, 5, 8 Calculating: Find the mean = (4 + 8 + 6 + 5 + 8) / 5 = 31 / 5 = 6.2 Subtract the mean and square the result: (4 - 6.2)^2 = 4.84, (8 - 6.2)^2 = 3.24, (6 - 6.2)^2 = 0.04, (5 - 6.2)^2 = 1.44, (8 - 6.2)^2 = 3.24 Now, add all squared values: 4.84 + 3.24 + 0.04 + 1.44 + 3.24 = 12.8 Divide by number of values to get variance: 12.8 / 5 = 2.56 Take the square root of variance = ?2.56 = 1.6 Output: Standard Deviation = 1.6
Steps to Calculate Standard Deviation
To calculate the standard deviation of the given data values, we followed these steps:
- We first created an array with five data values.
- Then, we calculated the sum of all values using a loop.
- Next, we divided the sum by the total number of elements in the set to calculate the mean.
- After that, we calculated the squared difference of each value from the mean and added them all to get the variance.
- Then, we divided the total variance by 5(total number of elements in set) to get the average variance.
- Finally, we took the square root of the variance to get the standard deviation.
C++ Program to Calculate the Standard Deviation
Below is a complete C++ program that calculates the standard deviation using the formula.
#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 values is: " << stdDeviation; return 0; }
Below is the output of the above program, which shows the standard deviation of the given inputs.
The data values are: 12.5 7 10 7.8 15.5 The standard deviation of these values is: 3.1232
Time Complexity: O(n) because we loop through the array three times.
Space Complexity: O(1).
Advertisements