Doing It Again
A loop repeats work without writing it out over and over, a set number of times, with a counter you can use as it goes.
To show the numbers 1 to 10 with what you know so far, you would write ten SHOW lines.
For 1 to 100, a hundred of them. Computers exist so that you never have to.
A loop does a piece of work over and over, as many times as you say, and you write that work once.
Count, without writing it out
FOR i = 1 TO 10
SHOW i
END
1 2 3 4 5 6 7 8 9 10
FOR i = 1 TO 10 starts a loop with a counter called i. END marks where the repeated
work stops. The computer runs everything between them with i set to 1, then runs it
again with i set to 2, and keeps going up to 10.
Three lines did the work of ten. Changing that 10 to 100 would do a hundred without
another keystroke. That is the point of a loop: how much repetition you get is a number
you set, not lines you type.
The counter is a value you can use
The counter is not only for keeping count. It is a variable, holding a different value each time round, and you can use it in the work:
FOR i = 1 TO 10
SHOW i, " times 7 is ", i * 7
END
| Pass | i | i * 7 | Shown |
|---|---|---|---|
| 1 | 1 | 7 | 1 times 7 is 7 |
| 2 | 2 | 14 | 2 times 7 is 14 |
| 3 | 3 | 21 | 3 times 7 is 21 |
| 10 | 10 | 70 | 10 times 7 is 70 |
Ten passes of the same two lines. Only i changes, and the computer works i * 7 out
afresh from it each time round.
A loop that counts and hands you the count is how you fill a row, draw a grid or lay out a level: anywhere the work is the same thing, once per number.
When it’s wrong, see why
- It runs once, or not at all. Check the range.
FOR i = 1 TO 1runs once.FOR i = 1 TO 0runs no times, because the start is already past the end. - The numbers are out by one.
1 TO 10gives ten passes.0 TO 10gives eleven. Decide whether you are counting things or counting from zero, then set the range to match. - Only part of the work repeats. The repeated work is everything between
FORandEND. A line outside them runs once, not once per pass.
What you’ve learnt
- A loop repeats work without you writing it out. How many times is a value you set.
- A counted loop runs a fixed number of times and keeps a counter that climbs as it goes.
- The counter is a variable you can use in the repeated work. That is what makes a loop build things rather than only count.
What’s next
A counted loop is for when you know how many times. Often you do not: you repeat until something happens. In Unit 2 we meet that loop, and use it to turn the guessing game into something you can play.