Programming Concepts - Repetition

Repetition

Repetition is simply repeating code – anywhere between once and forever. The need for repetition soon becomes clear early on when learning to code, however children don’t always automatically use it.

Going back to the ‘making a cup of tea’ analogy – think about when you stir the tea with a spoon. The whole act of stirring is a repetitive process ‘Draw the spoon in a circular motion around the cup’

Imagine listing the instructions to stir without a repeat: 
Pick up a teaspoon; 
Hold the spoon by the handle, place the other end into the mug; 
Draw the spoon in a circular motion around the cup; 
Draw the spoon in a circular motion around the cup; 
Draw the spoon in a circular motion around the cup; 
Draw the spoon in a circular motion around the cup; 
Draw the spoon in a circular motion around the cup; 
Draw the spoon in a circular motion around the cup; 
etc.

It would be much simpler to put in a repeat. We could specify how many times we wanted to stir the spoon e.g. 
Pick up a teaspoon; 
Hold the spoon by the handle, place the other end into the mug; 
Draw the spoon in a circular motion around the cup 10 times;

Notice how much shorter and more efficient the code is! Using a repeat loop within programming saves time, makes your code more efficient and it even saves space. It soon adds up!

Let’s look at a ‘Police Lights’ program. We are flashing a Sparkle in the following pattern: red-red-blue-blue. If we want to continue the program, we would have to write out the code over and over again. But what if we wanted to flash the lights for a really long time, or forever?

With the simple addition of a repeat loop, we are able to run the code for as long as we want. If we tried to replicate this, we would soon run out of memory, and effort!

This code can, however, be improved further. Given that we go red-red-blue-blue, with each instance of the colour shining for the same period, we can use another repeat!

Our code has become even more efficient! This also allows us to change it more easily. If we wanted to adjust the number of times each colour flashed before change it is just a case of adjusting a number.