The greenhouse team has a new request for Beacon. They want a water check every hour, all day and all night.
Comet grins and starts writing. Ten minutes later, her page is covered in the same two lines, copied again and again.
"Twenty-four copies," she says, shaking her hand. "Done. Mostly."
Wren scans the page. "What do you notice about lines three, five and seven?"
Comet looks closer. Line seven says waterLevl. She made a typo on copy number four.
Nova hovers over the page, her cyan lights blinking. "Would you like a hint?" she asks.
"What if you wrote the check once, and told Beacon how many times to do it?"
Wren smiles. "Then there would be only one place to fix a mistake."
How can a short program do a job a thousand times, and know when to stop?
This week you will write loops in pseudocode, trace them by hand and fix one that never stops.
Every algorithm can be built from three building blocks: sequencing, selection and iteration.
Sequencing means doing each step in the order it is given. You practiced it in week 2.
Selection decides which parts run, based on a true or false condition. That was week 3, with IF and ELSE.
Iteration is a repeating portion of an algorithm. It repeats a set number of times, or until a condition is met.
In everyday talk, programmers call a repeating portion a loop.
| Building block | What it does | Beacon example |
|---|---|---|
| sequencing | Runs steps in the order given | Read the sensor, then show the reading |
| selection | Chooses which steps run | IF the water is low, show an alert |
| iteration | Repeats steps | Check the water 24 times a day |
Here are the first two of Comet's twenty-four copies. In our Beacon pseudocode, INPUT() stands for reading a sensor.
waterLevel ← INPUT() DISPLAY(waterLevel) waterLevel ← INPUT() DISPLAY(waterLevel) ... 22 more copies ...
| About Comet's copies | True or false? |
|---|---|
| Forty-eight copied lines are easy to check for typos. | ? |
| If the team wants a check every half hour, Comet must copy even more lines. | ? |
| Iteration could let Comet write the check only once. | ? |
| Copying lines by hand is a kind of selection. | ? |
Loops are not only in programs. Many everyday instructions repeat a step.
Some repeat a set number of times. Others repeat until something happens.
Strong start, developer. Tomorrow you will write your first REPEAT loop for Beacon.