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 |
// arrays/average.cpp - Averages numbers
// Fred Swartz - 2003-11-20
#include <iostream>
using namespace std;
float sum(const float x[], const int size); // prototype
//====================================================== main
int main() {
float a[1000]; // Declare an array of 1000 floats
int n = 0; // number of values in a.
while (cin >> a[n]) {
n++;
}
cout << "Average = " << sum(a, n)/n << endl;
return 0;
}
//======================================================= sum
// sum adds the values of the array it is passed.
float sum(const float x[], const int size) {
float total = 0.0; // the sum is accumulated here
for (int i=0; i<size; i++) {
total = total + x[i];
}
return total;
}
|
Because this application reads an unbounded number of values, it is subject to buffer overflow, trying to read more values into an array than will fit. A more appropriate data structure to use is a vector, which will expand as necessary to accomodate data. See Passing Vectors as Parameters.