Iteration: WHILE and REPEAT
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
WHILE tests first
- A pre-condition loop tests the condition, then maybe runs the body.
- If the condition is already
FALSE, the body never runs. - The block ends at
ENDWHILE.
DECLARE N : INTEGER
N ← 3
WHILE N > 0
OUTPUT N
N ← N - 1
ENDWHILE
REPEAT runs, then tests
- A post-condition loop runs the body, then tests.
- The body runs at least once.
- The loop stops when the condition becomes
TRUE.
DECLARE N : INTEGER
N ← 0
REPEAT
N ← N + 1
OUTPUT N
UNTIL N = 3
Watch out
WHILEstops onFALSE.REPEATstops onTRUE. They are opposite tests.- Something inside a
WHILEmust change the condition, or the loop never ends.
Common mistakes
ENDWHILEcloses aWHILE.UNTILcloses aREPEAT.- A
REPEATthat should stop at 3 must updateNbefore the test.
Now you try
- Write one
WHILEand oneREPEAT.
Set N to 3. While N is greater than 0, output N and then subtract 1.
Click Run to see the output here.
Use REPEAT … UNTIL to output 1, 2 and 3.
Click Run to see the output here.