GoalUse a repeat block to replace blocks that repeat in the same order, and trace what the program does.
New words
repeat block · a block that runs the blocks inside it again and againloop · a part of a program that repeatsinside · between the arms of the repeat block
Explanation
Look at a dance with the same two moves again and again: right, left, right, left, right, left. We can write each move as a block, or we can use a repeat block and put the two moves inside it, with the number of times. The repeat block counts as one block, so the short program has far fewer blocks. Take care: only blocks that must happen again go inside the repeat. A block that should happen once, such as a go to block that resets the sprite, stays outside, before the repeat.
Worked examples
Start x: 0
Long program
Short program
after loop 1
20, then 0
20, then 0
after loop 2
20, then 0
20, then 0
after loop 3
20, then 0
20, then 0
In both programs the sprite moves 20 right and 20 left three times. It ends where it started. The long program has 7 blocks, and the short one has 4 (the hat, the repeat and the two blocks inside).
This program grows a sprite and waits, 4 times. Start with size 100. After each loop the size goes up by 10: 110, 120, 130, 140. Each loop waits 1 second, so the program takes 4 seconds.
A common mistake is putting the reset inside the repeat. Here the go to block puts the sprite back to x: 0 each time, so the sprite always ends at x: 10, not at x: 30. The reset belongs before the repeat.
Class activity
Repeat in real life (with a friend): choose a pattern of three moves, such as clap, stamp, turn. Do it 4 times without stopping. Then write it as a program: “repeat 4 times: clap, stamp, turn”. Count the blocks for the long version and the short version. How many blocks does the repeat save?
Practice
1
Count the blocks in the long program and in the short program in the explanation above.
The long program has 7 blocks, the short one has 4.
2
A sprite starts at size 100. What is its size at the end, and how long does the program take?
Size 50, because 100 − 5 × 10 = 50. It takes 5 seconds, 1 second for each loop.
3
Write a short program for: move 10 steps, turn ↻ 90 degrees, four times. Where does the sprite end?
repeat (4): move (10) steps, turn ↻ (90) degrees. It ends where it began and faces the way it started, because 4 × 90 = 360 degrees.
4
This sprite should grow to size 180, but it always ends at size 120. Why? How can we fix it?
The set size block is inside the repeat, so every loop puts the size back to 100 before it adds 20. Move “set size to (100) %” before the repeat. Then it grows 100 + 4 × 20 = 180.