Checking Before You Start
A loop that asks its question first, so the work can happen no times at all.
REPEAT asks its question at the bottom, after the work. That suits a guessing game: you
have to make one guess before anyone can say whether you were right.
Sometimes the work should not happen at all. Then the question goes first.
Ask, then work
WHILE checks before each pass, including the first one.
LET lives = 3
WHILE lives > 0 DO
SHOW "Lives left: ", lives
LET lives = lives - 1
END
SHOW "Game over"
Lives left: 3 Lives left: 2 Lives left: 1 Game over
The computer asks lives > 0, and runs the block only if the answer is yes. At the bottom
it goes back and asks again. When lives reaches 0 the answer is no, and the program
carries on below the END.
None is a real number of times
Start with no lives at all and the block never runs:
LET lives = 0
WHILE lives > 0 DO
SHOW "Lives left: ", lives
LET lives = lives - 1
END
SHOW "Game over"
Game over
That is the difference worth holding on to. A REPEAT always runs its work at least once,
because it does not ask until afterwards. A WHILE can run it no times.
Which you want depends on the work. Asking for a guess suits REPEAT: there is no answer
to check until somebody has guessed. Spending lives suits WHILE: a player with none
should not get a turn.
When it’s wrong, see why
- It never stops. Nothing inside the loop changes the answer to the question at the
top.
WHILE lives > 0needs something in the block to take a life away, or the answer stays yes forever. - It never runs. The question was already no on the first ask. That is not a fault in itself, but check it is what you wanted.
- You wanted it to run once whatever happens. That is a
REPEAT.WHILEpromises nothing about the first pass.
What you’ve learnt
WHILEasks its question first and runs the work only while the answer is yes.- A
WHILEcan run no times at all. AREPEATalways runs at least once. - Pick by the work: check first when doing it wrongly would be a mistake, check afterwards when there is nothing to check until you have.
- Something inside the loop has to change the answer, or it never leaves.
What’s next
Every box so far holds one value. In the next module, Structure, a box holds many of them at once, which is how a program keeps a high score table, a row of enemies or a level.