Comet tears up her twenty-four copies and starts fresh. This time the page has only a few lines.
"REPEAT 24 TIMES," she reads aloud. "Then the check goes inside the braces."
Wren leans in. "How will you know it really runs twenty-four times, and not twenty-three?"
Comet opens her mouth, then closes it again. She is not sure.
Nova projects a small grid in the air. "I found a pattern," she says.
"When you are not sure what a loop does, follow it one pass at a time and write down every value."
Wren grabs a pencil. "A trace table," he says. "Let's investigate."
A REPEAT n TIMES loop runs the statements inside its braces n times. Those statements are the loop body.
Here is Beacon's hourly water check, written once instead of twenty-four times.
REPEAT 24 TIMES
{
waterLevel ← INPUT()
IF (waterLevel < 30)
{
DISPLAY("The tomatoes need water")
}
} Notice that the loop body holds an IF statement. Iteration and selection can work together.
Each pass reads a new value, so waterLevel gets the most recent reading each hour.
Hand tracing means following a program by hand and writing down each value as it changes.
It is one of the most useful ways to find and correct errors.
A trace table has a column for each variable and a row for each step. Trace this short loop.
total ← 0
REPEAT 3 TIMES
{
total ← total + 5
}
DISPLAY(total) | Step | What happens | total |
|---|---|---|
| Start | total gets 0 | 0 |
| Pass 1 | total gets 0 + 5 | 5 |
| Pass 2 | total gets 5 + 5 | 10 |
| Pass 3 | total gets 10 + 5 | ? |
plantsChecked ← 0
REPEAT 6 TIMES
{
plantsChecked ← plantsChecked + 1
}
DISPLAY(plantsChecked) | Statement | True or false? |
|---|---|
| A statement after the closing brace runs once, after the loop ends. | ? |
| A statement inside the loop body runs once for every pass. | ? |
| REPEAT 6 TIMES runs its body seven times. | ? |
| A trace table needs a column for each variable. | ? |
Nice tracing. Tomorrow in Beacon Lab you will hunt down a loop that never stops.