fastread homefastrread library fastread menu

C++ : Calculate Standard Deviation

Tutorial by:Manisha Dubey      Date: 2016-06-18 04:52:38

❰ Previous Next ❱

In this program, elements of arrays are used for storing the data and this array is passed to function which calculates standard deviation and finally the result(standard deviation) is displayed in main() function.

Source Code to Calculate Standard Deviation by Passing it to Function


/* Source code to calculate standard deviation. */

#include <iostream>
#include <cmath>
using namespace std;
float standard_deviation(float data[], int n);
int main()
{
    int n, i;
    float data[100];
    cout << "Enter number of data: ";
    cin >> n;
    while (n>100 || n<=0)
    {
        cout << "Error! number should in range of (1 to 100)." << endl;
        cout << "Enter the number of data again: ";
        cin >> n;
    }
    cout << "Enter elements: " << endl;
    for(i=0; i<n; ++i)
        cin >> data[i];
    cout << endl;
    cout << "Standard Deviation = " << standard_deviation(data,n);
    return 0;
}
float standard_deviation(float data[], int n)
{
    float mean=0.0, sum_deviation=0.0;
    int i;
    for(i=0; i<n;++i)
    {
        mean+=data[i];
    }
    mean=mean/n;
    for(i=0; i<n;++i)
    sum_deviation+=(data[i]-mean)*(data[i]-mean);
    return sqrt(sum_deviation/n);           
}

 

 
 

Output


Enter number of datas: 4
Enter elements:
1
2
3
4

Standard Deviation = 1.11803

❰ Previous Next ❱


C++

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website