How do I total all the values in an array?
and average them?
How do I total all the values in an array?
and average them?
Wow, that's even simpler than I thought.Code:const int MAX = whatever; int array[MAX]; int sum = 0; for(int i = 0; i < MAX; ++i) { sum += array[i]; } double avg = sum / MAX;
FAQ
"The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.
"If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.
actually you may want to declare sum as a double, or typecast one of the ints in the division.
orCode:double sum = 0; //...
otherwise, you will get an int placed into a double, and the int will be output.Code:double avg = double(sum) / MAX;
You're absolutely right, Alpha. I just coded that out in like 30 seconds, so I overlooked that.
FAQ
"The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.
"If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.