Exercise:
Write a C++ program that uses arrays to calculate standard deviation of 5 data entries.
Click Here to View the Solution:
#include <iostream>
#include <cmath>
using namespace std;
float SD(float Data[]);
int main()
{
float Data[5]; //number of entries can be changed
cout << "Insert 5 Data entries:\n";
for(int x = 0; x < 5; ++x)
{
cout << x+1 << ". ";
cin >> Data[x];
}
cout << endl << "Standard Deviation is: " << SD(Data);
return 0;
}
float SD(float Data[])
{
float sum = 0.0, mean, ans = 0.0;
for(int x = 0; x < 5; ++x)
{
sum += Data[x];
}
mean = sum/10;
for(int x = 0; x < 5; ++x)
ans += pow(Data[x] - mean, 2);
return sqrt(ans / 5);
}
Click Here to View the Output:
Insert 5 Data entries: 23 3.5 13.63 9.2 10 Standard Deviation is: 8.75968
Click Here to View the Explanation:
- This code creates a user-defined function
SD()
. 5 entries are requested to be entered by the user. - After the user enters 5 elements, they are stored as an array.
- This function
SD ()
is then called in themain ()
function. Standard deviation for the entered numbers is calculated by the function. - The answer is printed on the screen.