C++ Notes: Example - Array maximum

Max value

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
//============================================= max
// From algorithms/arrayfuncs.cpp
// Returns the maximum value in an array.
float max(float a[], int size) {
    assert(size > 0);        // Note 1.
    float maxVal = a[0];     // Note 2.
    for (int i=1; i<size; i++) {
        if (a[i] > maxVal) {
            maxVal = a[i];
        }
    }
    return maxVal;
}//end max
Notes:
  1. Computing the maximum requires there is at least one value in the array. The "assert" enforces this requirement.
  2. The initial value for the maximum starts at the value of the first element instead of zero. Zero is commonly used, but doesn't work when all array elements are negative!

Max index

Another approach to the maximum is to return the index of the maximum value instead of the value. This is an advantage when the values are large or contain dynamically allocated values that makes assignment a non-trivial operation. Another reason to return the index is so that the value at that location in the array can be changed.
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
//============================================= maxIndex
// From algorithms/arrayfuncs.cpp
// Returns the index of the maximum value in an array.
int maxIndex(float a[], int size) {
    assert(size > 0);
    int maxIndex = 0;
    for (int i=1; i<size; i++) {
        if (a[i] > a[maxIndex]) {
            maxIndex = i;
        }
    }
    return maxIndex;
}//end maxIndex
Extracted from algorithms/arrayfuncs.cpp