Lesson 1 of 8
Loops and patterns
Learn how a loop repeats steps, how to spot patterns, and how to write long instructions in a short way.
Let us begin
The big idea
Clap, stomp, clap, stomp, clap, stomp. Writing that out is slow, but we can say repeat 3 times: clap, stomp. This short way of repeating is called a loop. Programmers use loops all the time.
A loop repeats a set of steps again and again. Instead of writing the same steps many times, we write them once and say how many times to repeat.
A pattern is something that repeats in a regular way, like red, blue, red, blue. Loops and patterns go together: if you can see the pattern, you can write a loop for it.
We can draw a square with a loop. Repeat 4 times: walk forward, turn right 90 degrees. The same two steps happen four times, so the loop is short.
A loop must know when to stop. A loop that never stops is called an endless loop, and the computer would be stuck repeating forever.
Number patterns work like loops too. In 3, 6, 9, 12, we start at 3 and add 3 each time.
Worked examples
See how it works
Counting actions
Repeat 4 times: clap, clap, stomp. In one round there are 2 claps and 1 stomp, which is 3 actions. After 4 rounds: 4 x 2 = 8 claps, 4 x 1 = 4 stomps, and 4 x 3 = 12 actions altogether.
Adding in a loop
Start with total = 0. For each number from 1 to 5, add it to the total. 0+1 = 1, 1+2 = 3, 3+3 = 6, 6+4 = 10, 10+5 = 15. The final total is 15.
A number pattern
The pattern is 3, 6, 9, 12. Each step adds 3, so the loop is: start at 3, add 3 each time. The next number is 12 + 3 = 15.
Drawing a square
Repeat 4 times: forward 3 steps, turn right 90 degrees. Walking 3 steps four times is 12 steps in all. You end up where you started, having walked a square.
Try it at home
Loop dance
You will need
- paper and pencil
- an open floor space
What to do
- Write a dance of 3 moves, such as clap, jump, spin.
- Write it as a loop: repeat 4 times: clap, jump, spin.
- Do the dance and count how many moves you did in all.
- Change the loop to repeat 2 times and see how the dance changes.
- Now draw a pattern of shapes with pencil and write the loop that makes it.
Ask a grown-up: Make sure the floor space is clear. Jumping and spinning are done at a gentle level, and nobody should feel hurried.
Fun fact
A loop saves effort: a computer can repeat a step a million times without getting bored or tired.
