go to previous page   go to home page   go to next page

Answer:

Three calls to maxThree() to get three contenders and a final call to get the winner should work.


Max Nine

If we can count on maxThree() meeting its exit conditions when the pre-conditions are true, then it can be used as a block, just as usual, even if its internal structure is not strictly structured.

/* Pre-condition: 9 integer arguments
   Exit condition: maximum argument returned.
*/
int maxNine(int a, int b, int c, int d, int e, int f, int g, int h, int i)
{
  int x, y, z;
  x = maxThree(a, b, c);
  y = maxThree(d, e, f);
  z = maxThree(g, h, i);

  return maxThree(x, y, z);
}

You might think that a good way to write this function would be to copy the nine integers to an array, sort the array into ascending order, and then return the rightmost element. This would be inefficient. Most of the effort in sorting would be wasted if all you want is the single maximum.


QUESTION 5:

Should an early return be used inside the body of a loop?