1
Repeat in an algorithm
Computing 2: Unit 8, pp. 106–121
GoalUse a repeat in an algorithm so that the same steps are not written again and again.
New words
repeat · to do the same steps againpattern · steps that come again and againshorter · with fewer steps
Explanation
Some paths have a pattern. The same steps come again and again. To draw a square, a robot goes forward and turns right, four times. We can write every step, or we can write “repeat 4 times” and put the steps inside. Both algorithms draw the same square. The repeat way is shorter and easier to read.
| Long way | Short way |
|---|---|
| forward 3 | repeat 4 times: |
| turn right | forward 3 |
| forward 3 | turn right |
| turn right | |
| forward 3 | |
| turn right | |
| forward 3 | |
| turn right |
Worked examples
The robot draws a square with sides of 3 steps. It starts at the top left, facing right.
A repeat can hold just one step. Five forwards in a row are the same as “repeat 5 times: forward”.
Only the steps that happen again and again go inside the repeat. A step that happens once stays outside. In this algorithm the last step, “forward 3”, happens once: start, marker down, repeat 2 times: [forward 2, turn right], forward 3, stop.
Class activity
Walk a repeat: with an adult, use a big space or chalk. Follow this algorithm: repeat 4 times: take 3 steps, turn right. What shape did you walk? Now follow this one: repeat 2 times: take 4 steps, turn right, take 2 steps, turn right. What shape is this? Count how many times you turned right in each walk.
Practice
1
Look at the path. The robot starts at the top left, facing right. Which steps come again and again? Write the algorithm with a repeat.
Forward 2, turn right, forward 2, turn left comes twice. Repeat 2 times: forward 2, turn right, forward 2, turn left.
2
Write the long version of: repeat 3 times: forward 1, turn left.
Forward 1, turn left, forward 1, turn left, forward 1, turn left.
3
Write the short version: forward 2, turn right, forward 2, turn right, forward 2, turn right, forward 2, turn right.
Repeat 4 times: forward 2, turn right.
4
How many turns does the robot make in: repeat 5 times: forward 1, turn right?
5 turns, one in each round.