So I am instructed to write a function that uses the following prototype:
double stats(int *array, int size, double *std_dev);
The function should return the average value of the array. The argument std_dev is passed by reference so that the standard deviation of the data in the array can be returned. I assume this to mean that I need to calculate standard deviation as well.
I set about this in the following manner:
double stats(int *array, int size, double *std_dev){
int sum = 0; //declare int to hold sum
int i; //index used in for-loops
for (i = size; i>0; i--){ // for every element(i)
sum += array[i]; //add array element to
}
int mean = sum/size;
for (i = size; i>0; i--){ // for every element(i)
sum += array[i] -mean;
}
return 0;
}
The code compiles; but I'm not quite sure if these lines actually do what I think they do, and I don't have parameters to test with:
sum += array[i]; //add array element to
sum += array[i] -mean;
I know that "array" is a pointer variable, but I'm not exactly sure what it is my code is actually doing, can someone please tell me what these lines actually do? Thanks.
EDIT: I am aware that this code does not completely satisfy my objective, it is a WIP that compiles.
EDIT EDIT: That includes the logical correctness of my program.
2 Answers 2
when you do this
sum += array[i];
you are iterating through every element of the array - i.e., element at each index and storing the result in the variable sum.
a[i] is the ith element of the array a. It can be thought of as *(a+i).
Similarly in the second loop, you are adding up a[i] - sum to the variable sum. I think you are trying to compute the standard deviation in the second loop in which case you need to sum (a[i] - mean)^2 (i.e, square of difference from the mean) into the variable std_dev and then divide by size.
3 Comments
a[i] - mean^2" o0 I guess you meant mean in power of 2 and not xor 2 right ?you have problems in your for:
you will never get to array[0] which is the first element in array
use for(i=0;i<size;i++)as for your question
sum +=array[i]; will put in variable sum the result of sum + array[i]
sum += array[i] -mean; will put in sumthe result of array - mean
BTW I have no idea what are you doing in second for loop (mathematically)
but if you don't want to use previous sum which contain the sum of all the array then you
should to set sum to 0 before you run the second for.
BTW, you returning 0
don't you want to return your average which is return mean; in your case ?
in function prototype it says function should return double
what you've done is int mean = sum/size; is an integer value that will cut the numbers after the "."
you probably want to use double mean = sum/size;
and then to return it as I have mentioned before.
array[i]is the i-th element of the array i.e. the element in i-th location from start index.