More complex code uses loops or ‘repeat’ blocks to run a sequence of steps many times. Imagine a robot that made 100 cakes each day. You could give it 100 recipes that are all exactly the same OR you could give it 1 recipe and program it to use (run) the recipe 100 times – that’s a loop! Let’s look at a Scratch example (click the green flag to run the code):

This example uses the repeat block to run the 4 code blocks inside it 100 times! If you didn’t use the repeat blockĀ  you would need 400 blocks of code to do the same thing! Coding using loops is much faster to write and easier to change. There’s also less chance for errors (code bugs) to sneak into your project. When it comes to coding – small is beautiful!

Infinite Loops – Repeat Forever

In the natural world there are many loops that we can observe. Each day the sun rises in the east, makes its way across the sky and sets in the west. It’s a loop – one that goes on and on forever. We call this an infinite loop and in scratch we use the ‘repeat forever’ block to create one. Of course, code doesn’t really run ‘forever’ – once we click the stop button or shutdown the browser (or computer) it does stop. However, there are many times that we simply want the code to keep running and an infinite loop does this for us. Let’s look at another example:

In the code above, the bus changes colours and rotates slightly until the stop button is clicked. This kind of infinite loop is used a lot in games. For example, in Minecraft, animals like sheep walk around, stop and eat grass. These actions are in a ‘forever loop’. They can be interrupted if the animal dies or falls into water. In Scratch we can use the ‘stop’ block to interrupt a ‘repeat forever’ block.