Iteration: WHILE and REPEAT · การทำซ้ำ: WHILE และ REPEAT
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.
WHILE ทดสอบก่อนแต่ละรอบ
- ลูป
WHILEตรวจสอบการทดสอบ ก่อน รอบถัดไป - ถ้าการทดสอบเป็นเท็จตั้งแต่ต้น บล็อกจะรัน ศูนย์ ครั้ง
- Block สิ้นสุดที่
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.
REPEAT ทดสอบหลังแต่ละรอบ
- ลูป
REPEATตรวจสอบการทดสอบ หลัง รอบถัดไป - ดังนั้นบล็อคจะรัน อย่างน้อยหนึ่งครั้งเสมอ
- มันสิ้นสุดที่
UNTIL
N ← 0
REPEAT
N ← N + 2
OUTPUT N // 2, 4, 6
UNTIL N >= 6
REPEAT runs, then tests · REPEAT ทำงานก่อนแล้วจึงทดสอบ
WHILE tests before (may run 0 times); REPEAT tests after (runs at least once). · WHILE ทดสอบ ก่อน (อาจทำงาน 0 ครั้ง); REPEAT ทดสอบ หลัง (ทำงานอย่างน้อยครั้งเดียว)
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.
ระวัง
- สิ่งบางอย่างภายในลูปต้องทำให้การทดสอบเข้าใกล้จุดหยุดลง มิฉะนั้นจะรันตลอดไป
WHILEอาจรัน 0 ครั้ง;REPEATจะรัน อย่างน้อย 1 ครั้งเสมอ
Common mistakes
WHILEtests the condition first;REPEAT ... UNTILtests after, so it runs at least once.- Change something inside, or the loop never ends.
ข้อผิดพลาดที่พบบ่อย
WHILEตรวจสอบเงื่อนไขก่อน;REPEAT ... UNTILตรวจสอบหลัง ดังนั้นจึงทำงานอย่างน้อยหนึ่งครั้ง- เปลี่ยนค่าภายใน หรือลูปจะไม่มีวันสิ้นสุด
Now you try
- Pick
WHILEorREPEATfor each task. - Press Check answer to test it.
ลองดูเลย
- เลือก
WHILEหรือREPEATสำหรับแต่ละงาน - กด Check answer เพื่อทดสอบ
Use a WHILE loop to output 1, 2, 3, one per line. · ใช้ลูป WHILE เพื่อแสดงผล 1, 2, 3, หนึ่งต่อบรรทัด
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Use a REPEAT loop to output 2, 4, 6, one per line (add 2 each time, stop at 6). · ใช้ลูป REPEAT เพื่อแสดงผล 2, 4, 6, หนึ่งต่อบรรทัด (เพิ่ม 2 ทุกครั้ง, หยุดที่ 6)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Use a WHILE loop to add up 1 to 4, then output the total (it is 10). · ใช้ลูป WHILE เพื่อรวมผลตั้งแต่ 1 ถึง 4, แล้วแสดงผลรวม (ซึ่งมีค่า 10)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่