Iteration: WHILE and REPEAT
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 Counter : INTEGER
Counter ← 3
WHILE Counter > 0
OUTPUT Counter
Counter ← Counter - 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 Counter : INTEGER
Counter ← 0
REPEAT
Counter ← Counter + 1
OUTPUT Counter
UNTIL Counter = 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
Trace a starting value of zero as well as a positive value. Decide whether any output should happen before the first condition test. Do not combine the opening of one loop type with the ending of another.
ENDWHILEcloses aWHILE.UNTILcloses aREPEAT.- A
REPEATthat should stop at 3 must updateCounterbefore the test.
Now you try
- Write one
WHILEand oneREPEAT.
Independent transfer
The final task has no supplied algorithm. Plan its inputs, processing and outputs, then solve it before opening support. Check more than the sample case.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Set Counter to 3. While Counter is greater than 0, output Counter and then subtract 1.
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Use REPEAT … UNTIL to output 1, 2 and 3.
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Read integers until 999. Output how many negative values were entered; exclude 999.
Click Run to see the output here.