C++ Notes: Example - Array average

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
//=============================================== avg
// From algorithms/arrayfuncs.cpp
// Returns the average of a[0]..a[size-1].
float avg(float a[], int size) {
    assert(size > 0);
    float sum = 0;
    for (int i=0; i<size; i++) {
        sum = sum + a[i];
    }
    return sum / size;
}//end avg
The size must be greater than zero otherwise the division at the end will cause problems.