Wren pins a printout to the greenhouse board. It is Beacon's new tank fill routine, and it has a problem.
"In the paper test, the tank should stop filling at 75," he says. "But the trace just keeps going."
Comet frowns. "The loop says stop at 75. I wrote it myself."
Nova hovers beside the printout and dims her lights to lab mode. "Let's debug together," she says.
"Count every pass. Write every value. The loop will tell you its own secret."
Comet hands out pencils. Wren draws the first column of a trace table.
"What do you notice," Wren asks, "about the numbers the tank can reach?"
You will hand trace Beacon's fill loop with a counter and find out why it never stops.
Then you will fix the stop condition and trace the fixed loop to prove it works.
Remember: with REPEAT UNTIL, the condition is checked before each pass.
waterLevel ← 40
passes ← 0
REPEAT UNTIL (waterLevel = 75)
{
waterLevel ← waterLevel + 10
passes ← passes + 1
}
DISPLAY("Tank full") | Pass | waterLevel | passes | Is waterLevel equal to 75? |
|---|---|---|---|
| Start | 40 | 0 | no |
| 1 | 50 | 1 | no |
| 2 | 60 | 2 | no |
| 3 | ? | 3 | ? |
| 4 | ? | 4 | ? |
Copy this table onto paper and keep going past pass 4.
| What the trace shows | True or false? |
|---|---|
| waterLevel always ends in a zero, so it can never equal 75. | ? |
| The loop stops after pass 4 because 80 is more than 75. | ? |
| This is an infinite loop: its ending condition never becomes true. | ? |
| The counter passes would keep growing for as long as the loop runs. | ? |
Wren suggests a new condition: stop when waterLevel is at least 75.
Here is the fixed line. Trace the fixed loop from 40 again.
REPEAT UNTIL (waterLevel ≥ 75)
| About the fix | True or false? |
|---|---|
| Changing equals 75 to at least 75 makes the loop stop. | ? |
| The fixed loop still runs forever if the tank starts at 40. | ? |
| A fixed loop should be traced again to prove the fix works. | ? |
Great debugging, developer. Tomorrow you will choose between loops and explain your choice.