Loops activities

Most programming languages have a range of different 'looping' contructs (Blocks). If you view the 'Control' pallet in Sense you will find there are several ('forever', 'repeat', 'repeat until' for example).

Here we will just quickly explore the 'repeat <n>' loop which repeats a set of one or more other Blocks 'n' times.

Our first use of a loop is very simple. A variable is used to keep a count of the number of times a loop has been executed so far. This is set to zero before the loop block. The repeat loop is set to perform the enclosed blocks '10' times and includes two blocks. The first block inside the loop adds '1' to the 'times done' variable and the second waits for 1 second. So the 'times done' variable's value will be the same as the number of times the loop has been executed.

simple loop stack in Scratch
Figure 1 Simple loop Stack

The program is shown in Figure 1 and is simple to construct or can be downloaded. Before you run the Stack select the 'Edit' menu's 'Set single stepping...' option and then select 'Flash blocks (slow)' so that Blocks are highlighted as they are executed. Then run the Stack and observe the value of 'times done' as the loop is repeated. When the loop has completed 10 times the Stack will finish.

The loop employs a fixed value of '10' to specify how many times the loop should be executed. We might want to vary the number of times the loop is performed according to the value of some other data. To do this we can replace '10' with another variable which gains a value from somewhere else in the stack. We can, for example, use the 'pop up and get input' Block from the 'input' pallet, which we used earlier, to obtain a value for the number of times the loop should be performed.

Alter the stack so that it is as shown in Figure 2 (or download the program).

simple loop using a variable.
Figure 2 Simple loop using a variable.

We have added a 'change' block to the loop so that the value of the 'times done' variable is increased each time the loop is executed. The loop is also executed according to the value in the 'times to do loop' variable which will have whatever value you type in when the earlier 'pop up' block is executed. Be sure to type in a number, such as '3', when asked and not something else such as a word 'hi' as a loop can't be executed 'hi' times; it makes no sense.

When you run the Stack you might want to turn on 'stepping' (ajust the slider at the right of the Sense window) again to see how the blocks are executed more clearly.

That's all on 'loops' (or 'repetition'). Please go back and continue onto the next activity.