C++ Variance and Standard Deviation

I have to write a program to calculate sum, mean, variance, and standard deviation and I was able to do the sum and mean but I don't understand the variance and standard deviation.

If the size of the set is 7 and the set is represented by X[0], X[1], X[2], X[3], X[4], X[5], X[6], then the (biased) variance may be computed as:


variance = [(X[0]-mean)2 + (X[1]-mean)2 + ... + (X[6]-mean)2]/7 and the standard deviation is the square root of the variance (use sqrt() in <math.h> to calculate square root of a value)

Run your program two times, using two different sets of data:

· Run I: 7 numbers --- 12, 22, 34, 43, 45, 54, 99

· Run II: 8 numbers -- 1.0, 1.5, 2.5, -9.3, 0, -1.0, 3.0, 6.4


Can anyone help? Here is my code so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// average2.cpp
// This program calculates the average of any number of numbers.
// Using the for structure

#include <iostream>

using namespace std;

#include <iostream>

int main()

{

   int n, count;

   float x, sum, avg, vari, sd;

   sum = 0;

   cout << "How many numbers?  ";

   cin >> n;

   for (count=1; count<=n; count++){

       cout << "?  ";

         cin >> x;

        sum = sum + x;

   }  //end for

   avg = sum / n;

   
   
   //output 
   cout << "The sum is  " << sum << endl;
   
   cout << "The average is  " << avg << endl;
   
   cout << "The variance is  " << vari << endl;
   
   cout << "The stanard deviation is  " << sd << endl;
      
   system ("pause");
   
   return 0;   //successful termination

} //end main 
you can use for loop for calculating variance, it's very simple:
1
2
3
for (int i = 0; i < 7; ++i) {
     variance += (x[i] - mean) * 2;
}
Topic archived. No new replies allowed.