Loops: repeating instructions — Computing, 11–13 years
A loop repeats instructions, either a set number of times or while a condition remains true.
What a loop does
A loop tells a program to run the same instructions again instead of copying them many times. It needs a way to stop, such as counting to ten or waiting until a condition becomes false. Each repetition is called an iteration.
Why loops matter
Many computer tasks involve doing a small action hundreds or millions of times: checking pixels, reading items or updating a game world. Copying the instructions would be long and error-prone. A loop keeps one pattern in one place and makes its stopping rule visible.
Worked example: counting by twos
Start number at 0. Repeat four times: add 2 to number, then display it. The displayed results are 2, 4, 6 and 8; the loop stops because it has completed four repetitions. Without the loop, you would write the add-and-display pair four times.
Trap: a loop that never stops
A loop can run forever if its stopping condition never becomes true, or if the value it checks never changes. This is easy to do because each line may look correct on its own. Check that every repetition moves towards the stopping point, such as increasing a counter from 0 to 5.
Where loops appear
Games use loops to update movement and redraw the scene many times each second. Music software can repeat a beat, and a spreadsheet can apply the same calculation down a column. In each case, repetition is useful because the same pattern is applied to changing items.
Keep exploring
Other languages
Loading MyLeoNes™…