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 before each pass
- A
WHILEloop checks its test before each pass. - If the test is false at the start, the body runs zero times.
- The block ends at
ENDWHILE.
Count ← 1
WHILE Count <= 3 DO
OUTPUT Count // 1, 2, 3
Count ← Count + 1
ENDWHILE
REPEAT tests after each pass
- A
REPEATloop checks its test after each pass. - So the body always runs at least once.
- It ends at
UNTIL.
N ← 0
REPEAT
N ← N + 2
OUTPUT N // 2, 4, 6
UNTIL N >= 6
Explore
REPEAT runs, then tests
WHILE tests before (may run 0 times); REPEAT tests after (runs at least once).
Watch out
- Something inside the loop must move the test toward stopping, or it runs forever.
WHILEmay run 0 times;REPEATalways runs at least 1 time.
Common mistakes
WHILEtests the condition first;REPEAT ... UNTILtests after, so it runs at least once.- Change something inside, or the loop never ends.
Now you try
- Pick
WHILEorREPEATfor each task. - Press Check answer to test it.
Use a WHILE loop to output 1, 2, 3, one per line.
Click Run to see the output here.
Use a REPEAT loop to output 2, 4, 6, one per line (add 2 each time, stop at 6).
Click Run to see the output here.
Use a WHILE loop to add up 1 to 4, then output the total (it is 10).
Click Run to see the output here.