A loop is a sequence of instruction that is repeated for a specified number of times or until a particular outcome is reached. This lesson introduces the idea and how they can use loops in coding
- Explain what loops are in coding
- Write a simple program incorporating a loop
What are loops?
Explain to pupils that one thing that computers are really good at is repeating commands. Much better than people are. Ask them what would happen if they had to do the same task over and over and over again. Maybe a thousand times over or for hours and hours. You will probably get answers such as
- “You’d get bored”
- “It would take for ever”
- “You’d get tired”
- “You might start making mistakes”
Explain that computers can do the same thing over and over – maybe for a million or a billion times and not get bored or tired. What’s more, they can do it very fast and every time they do it is exactly the same.
If you write code to tell a computer to do something lots of times, it’s called a loop.
https://studio.code.org/s/frozen/stage/1/puzzle/1 Kids love this programme as in is based on Elsa from Frozen skating over ice and leaving tracks in the ice. It is based on a drag and drop block programme similar to Scratch. You should complete the first few exercises to start with (drawing lines and a square) even though they are not actually about loops – but it is a pre-requisite bit of understanding. Then there is a useful video about Loops, which is easy to understand, and some more exercises on programming loops.
Using Scratch or Scratch Junior
You can, of course, use any other coding programme you use to demonstrate this. For example, if you use Scratch, select the ‘move forward block’. Run the program and see what happens to the ‘sprite’ (the little cat). Then drag another ‘move forward’ block underneath it and run it again. Do this 4 or 5 times until you have a stack of identical ‘move forward’ blocks. Then clear the screen, drag one ‘move forward’ block in, drag a repeat bracket around it and type the figure 5. Run the programme again.
Ask what are the advantages in creating a loop as opposed to dragging in 5 ‘go forward’ blocks.
Add an extra command inside the bracket, such as ‘turn right 90 degrees’, put x 4 as the number of repeats. Ask the class if they can visualise in their heads what shape the sprite might walk in. If they find that too hard, they could draw it on paper. Making predictions about what a programme will do is an important skill.
In Scratch Junior, you can do the same thing and we have written a whole lesson on this as part of the Learning to use Scratch Junior set of lessons.