การทำซ้ำ: WHILE และ 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 Money : REAL
DECLARE Years : INTEGER
Money ← 100
Years ← 0
WHILE Money < 1000 DO
Money ← Money * 2
Years ← Years + 1
ENDWHILE
OUTPUT "Years to reach 1000: ", Years
Test Money < 1000 |
Body runs? | Money after |
Years after |
|---|---|---|---|
100 < 1000 TRUE |
yes | 200 | 1 |
200 < 1000 TRUE |
yes | 400 | 2 |
400 < 1000 TRUE |
yes | 800 | 3 |
800 < 1000 TRUE |
yes | 1600 | 4 |
1600 < 1000 FALSE |
no: the loop ends | 1600 | 4 |
- Start with
Money ← 2000and the first test isFALSE: the body never runs and the output is0.
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 Total, Throws : INTEGER
Total ← 0
Throws ← 0
REPEAT
Total ← Total + 7
Throws ← Throws + 1
OUTPUT "Throw ", Throws, ": total ", Total
UNTIL Total > 20
- The body runs, then
UNTILtests. After three throws the total is 21, soTotal > 20isTRUEand the loop stops. - Start with
Total ← 50and the body still runs once, because the test comes at the end.
REPEAT: ทำงานในส่วนคำสั่งก่อน แล้ว UNTIL จึงทดสอบ
ลูปหยุดเมื่อ Total > 20 มีค่าเป็น TRUE
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. Decide first: may the body run zero times (WHILE), or must it run at least once (REPEAT)?
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.
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
ตั้ง Counter เป็น 3. ในขณะที่ Counter มากกว่า 0, เอาต์พุต Counter และจากนั้นลบ 1
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
ใช้ REPEAT … UNTIL เพื่อเอาต์พุต 1, 2 และ 3
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
อ่านค่าจำนวนเต็มจนกว่าจะเจอ 999 แสดงจำนวนของค่าลบที่ถูกป้อนเข้า; ไม่รวม 999
คลิก Run เพื่อดูผลลัพธ์ที่นี่