Google News
logo
C++ Program to Calculate Standard Deviation
In the following example of C++ program to calculate the standard deviation of a set of numbers :
Program :
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int n;
    float sum = 0, mean, stdDev = 0;

    cout << "Enter the number of elements: ";
    cin >> n;

    float arr[n];

    cout << "Enter " << n << " numbers: ";

    for(int i = 0; i < n; i++) {
        cin >> arr[i];
        sum += arr[i];
    }

    mean = sum / n;

    for(int i = 0; i < n; i++) {
        stdDev += pow(arr[i] - mean, 2);
    }

    stdDev = sqrt(stdDev / n);

    cout << "The standard deviation is " << stdDev << endl;

    return 0;
}
Output :
Enter the number of elements: 3
Enter 3 numbers: 2
5
9
The standard deviation is 2.86744
* This program prompts the user to enter the number of elements, creates a float array of that size, and prompts the user to enter numbers for the array.

* It then calculates the mean of the numbers in the array and uses that to calculate the sum of the squared differences from the mean.

* Finally, it takes the square root of the average of these squared differences to find the standard deviation, and prints out the result.