Repeat until a condition is met

Computer Science · Key Stage 2 · The School

Two kinds of loop

A COUNT-CONTROLLED loop repeats a fixed number of times: repeat 4 times. A CONDITION-CONTROLLED loop repeats until something becomes true: repeat until the score reaches 10. The first knows in advance how many times it will run. The second does not. Reading a loop's own words is usually enough to tell which kind it is.

Repeat until

"Repeat until the door is open" keeps trying the handle for as long as it takes. It might run once, or many times. It checks the condition, and only stops once that condition is true. Nobody could say in advance exactly how many tries that would take. The loop does not care how many times it runs, only whether the condition is finally met.

Choosing the right loop

Use a count-controlled loop when you know the number in advance, like drawing a square with exactly four sides. Use a condition-controlled loop when you do not know the number in advance, like collecting coins until none are left. Picking the wrong one usually shows up straight away, once the program runs.

A loop that never stops

"Repeat until the score reaches 10" only stops if something inside the loop actually changes the score. Forget to add points anywhere inside it, and the score stays at 0 forever, and the loop never ends. The condition has to have a real chance of becoming true. Testing a new loop by watching it run for a few seconds is how this kind of bug is usually caught. A program that never finishes is often stuck in exactly this way.

The School — all subjects · Knowledge map