Iteration

Iteration is the second basic concept in compter programming and is the repetition of a sequence of commands (known as a loop). The control blocks in Scratch allow for interation, in particular the forever and repeat blocks.

A square, for example, has four sides and can be drawn by repeating the sequence MOVE 60 TURN 90 four times. Double click on the outermost control block to start the sequence and remember to have the pen down if you want the sprite to draw a trail.

Experiment with different angles and sequences of commands to produce interesting shapes.

Flowers are produced by drawing a simple shape and then turning a little before repeating the shape to form a flower. The following example is a square flower but you can experiment with triangles and hexagons and other shapes.

The above example has a repeat iteration nested within another iteration.

A forever loop combined with a random number can produce continuous random behaviour easily.

Note the prescence of a wait command within the forever block. This is essential programming practise for applications that have more that one sprite so that the forever loop does not hog all the processing power and prevent the commands for other objects from running in a timely fashion.

Young programmers should master the creation of triangles, squares, and hexagons using iteration and then move on to creating flowers. Continuos motion can be implemented on the onekey application with the following loop:

This loop can be attached to the green flag control block so that the sprite begins moving as the application is started. The onekey commands will still work with this sprite and the updated onekey application is available here. Ask the programmers to update their own onekey application to have a continuosly moving sprite.

You can add a second sprite to the application. In this case we want the same command sequences and key press controls to work on the second sprite so the most effective way to duplicate the sprite is to export it and import it back into the application. Change the sprite costume and the initial starting position and you have created the iteration application.

11/12/2024 06:16:30