Check a procedure against a counterexample — quick review
A procedure can look right and be wrong.
A test case is an allowed input together with the output expected for it. In this unit the expected output is worked out by hand before the procedure is carried out. A procedure passes a test when it announces that output. An allowed input for which it announces anything else is a counterexample, and one counterexample shows that the procedure does not solve the problem. Passing tests cover only the inputs tried.
Take the table of inputs and correct outputs made with the problem statement, as in lesson 1.
Add inputs at the extremes of what is allowed, such as the smallest allowed row. Add unusual rows too: a row with a repeated value, and a row whose numbers are all below zero.
Trace the procedure on each input, and write what it announces beside the expected output.
Mark each row pass or fail. A failed row is a counterexample.
For a counterexample, identify the error and correct it. One way to find it is to look for the first step where the trace differs from a correct run. Correct that step and any later step that depends on it.
Carry out every test again after the correction, including the tests that passed before.
After several passing tests it is tempting to call the procedure correct. The three rows that pass all hold a number above 0, which hides the mistake. The changed procedure fails only on rows whose numbers are all below 0. Choose tests that differ from each other in kind, including inputs at the extremes of what is allowed.
A second slip is patching the counterexample alone, for instance with a new step that announces -3 for that one row. The row -9 -4 would then fail in the same way. Correct the steps that cause the error by restoring the first two steps of the largest-card procedure of lesson 2. Step 1 takes the first card and writes its number on the slip, and step 2 goes on with the cards that are left.