Debugging Loops


Inserting writes

If your loop is not working, a good way to find out what is wrong is to turn on the lights by showing the values of the loop control variables as the loop runs. But never just write out raw numbers. Always say who is talking. For example, suppose that you have a loop with loop control variables k and r. Give the loop a name (typically involving the name of the function or procedure that contains the loop). For the first loop in function f, you would add

  While ...
    Displayln "f: (loop 1): k = " ++ $(k) ++ "  r = " ++ $(r).
    ...
  %While
Even show values that you think you know. Remember that the program is not working, so there is a mistake in your reasoning somewhere.


Problems

  1. [solve] Insert prints into the following loop to see what the values of k and sum are each time the loop enters its body. Be sure to identify who is talking, and what it is showing. Do not show raw numbers.

      Let sum = 0.
      Let k = 0.
      While k <= 10 do
        Relet k = k + 1.
        Relet sum = sum + k.
      %While
    


Summary

Debug loops by adding prints to see what is happening. Turn on the lights.


Review

Taking care in designing a loop will reduce the amount of time you spend debugging it. There are two main ways to design a loop.

  1. [Action-based approach] Think carefully about how you want to start up the loop and what actions you want the loop to do over and over. Try doing it by hand before writing it in a program.

  2. [Information-based approach] Think carefully about the variables that you should use and how you want them to change. Think about relationships that you want them to have each time the program gets to the beginning of the loop. Then design the actions in the loop so that they do just what your plan calls for.