MyLeoNes™

Loops: repeating instructions — Technology, 7–10 years

A loop lets a computer repeat a small set of instructions instead of writing the same steps again and again. It is useful when a job has a repeating pattern.

Do it again, neatly

A loop is a part of a program that runs the same instructions several times. The program can repeat a set number of times, or continue while a condition is true, such as “keep moving until you reach the edge”.

Why use a loop?

Writing “move, move, move” 100 times would take a long time and make mistakes likely. Loops were created to describe repeated work briefly, so a program is shorter, clearer and easier to change.

Drawing a square

To draw a square, a robot can repeat two instructions four times: move forward 20 centimetres, then turn right 90 degrees. After one round it has one side; after four rounds it has four equal sides and returns to its starting direction.

Repeating the wrong thing

A loop does exactly what it was told, even when the repeating instructions are wrong or the count is off by one. It is reasonable to focus on the first successful step, but you must also check the turn, the number of repeats and the stopping condition.

Patterns in games and art

Loops make a game character walk ten steps, make music repeat a beat, or place twenty stars across a picture. They also control repeated jobs in real machines, such as checking a temperature again and again.

Keep exploring

Other languages

Loading MyLeoNes™…