The greenhouse team sends two more jobs for Beacon.
The first: take a photo of the herb shelf every hour for a whole day.
The second: tell Lena to keep the misting fan on until the air is damp enough.
Comet reaches for REPEAT 24 TIMES for both. "It worked last time," she says.
Wren tilts his head. "How many times will the fan need to run?"
Comet pauses. "It depends on how dry the air is. Nobody knows ahead of time how many checks it needs."
Nova blinks thoughtfully. "Interesting," she says. "Then maybe the second job needs a different kind of loop."
"Two jobs, two tools," Wren says. "Let's compare them."
A REPEAT UNTIL loop runs its body until a condition becomes true.
The condition is checked before each pass. If it is already true at the start, the body never runs at all.
If the condition can never become true, the loop never ends. That is an infinite loop.
humidity ← INPUT()
REPEAT UNTIL (humidity ≥ 60)
{
DISPLAY("Keep misting the herbs")
humidity ← INPUT()
} Look at the last line of the body. It reads the sensor again, so humidity can change each pass.
Without that line, humidity would never change, and a dry start would mean an infinite loop.
| Loop | Use it when | Beacon job |
|---|---|---|
| REPEAT n TIMES | You know how many passes you need | A photo every hour for 24 hours |
| REPEAT UNTIL | You stop when a condition becomes true | Mist until the air is damp enough |
Algorithms can be written in different ways and still do the same task.
But algorithms that look similar can also give different results. Compare these two loops.
Loop A Loop B
level ← 50 level ← 50
REPEAT UNTIL (level > 70) REPEAT UNTIL (level ≥ 70)
{ {
level ← level + 10 level ← level + 10
} } Good developers explain why they chose a control structure, not just which one.
Readability is how clear a program is to other programmers. Documentation can improve it.
One loop of eight lines is easier to read and fix than forty-eight copied lines.
| Statement | True or false? |
|---|---|
| If a REPEAT UNTIL condition is true at the start, the body runs once anyway. | ? |
| A REPEAT UNTIL loop whose condition never changes can become an infinite loop. | ? |
| Two loops that look almost the same can end with different values. | ? |
| A loop is usually easier to read than many copied lines. | ? |
Sharp thinking. Tomorrow is Impact Friday: what happens when a loop reaches thousands of people?