Standard Deviation with Arrays

Define a function that takes an array as its argument and returns the standard deviation of the array. The function should have at least two arguments, an array parameter and a type int parameter that gives the number of array position used. You may define the function either as a valued function or void function.

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
53
#include <iostream>
#include <cmath>
using namespace std;

double deviation(double[] , int);
double mean (double[] , int);
double mean2;

int main ()
{

int size=10;
double x[10];
mean2=0;

cout << "Enter ten numbers: ";


for (int i=0; i<10; i++)
{
cin>>x[i];
}

cout << "The standard deviation is: " << deviation (x,10) << endl;
return 0;

}

double mean(double x[], int size)
{
double sum=0;

for ( int i = 0; i <=size; i++ )
{
sum += x[i];
}
mean2=sum/10;
return mean2;
}

double deviation (double x[], int size)
{
double deviation;
double sum2=0;

for ( int i = 0; i <=size; i++ )
{
sum2 += pow((x[i]-mean2),2);
}
deviation= sqrt(sum2/(size-1));
return deviation;
} 


The standard deviation is incorrect, and i don't believe i'm making proper use of the question requirements. Help!
nothing is calling the mean.

So when you run your stdev, your mean is always 0 because that's what you initialized it to in main.
Even if you take out line 14, it still doesn't work.... Same answer as I got before.
one problem is what oghmaosiris said. Try mean2=mean(x,10); before calling deviation(x,10). another problem (inside both mean and deviation functions) is this:
for ( int i = 0; i <=size; i++ ). it should be like this:
for ( int i = 0; i < size; i++ ) (you should use '<' and not '<=')

I believe that if you take care of these two things your program will run fine! :)
also, mean2 isn't used in main, so why is it a global variable? '(even if it was used in main, why is it a global variable anyways?)

you should declare and initialize it in deviation since that's where you're going to need the value of mean and that's what mean() is going to return.
Thanks everyone. I got it to work.
ashgurlie
Would you post the new code PLEASE?
I think your code need Pause.
1
2
system("pause");
return 0;
Here is a suggestion for future reference. Use constants. Use the constant for all of your array loops. If the program ever needs to change you can simply change the value of the constant.
1
2
3
4
5
6
7
8
9
10
const int SIZE=10;
double x[SIZE];
mean2=0;

cout << "Enter ten numbers: ";

for (int i=0; i < SIZE; i++)
{
   cin>>x[i];
}


The other suggestions are good as well. mean2 shouldn't be a global. It is a better practice to declare variables at the lowest possible scope.
Topic archived. No new replies allowed.