Iteration: FOR · การทำซ้ำ: FOR
FOR repeats a fixed number of times
- A
FORloop counts from a start value to an end value. NEXTmarks the end of the loop body.
FOR I ← 1 TO 5
OUTPUT I // 1, 2, 3, 4, 5
NEXT I
A running total
- Start a total at 0, then add to it inside the loop.
Total ← 0
FOR I ← 1 TO 10
Total ← Total + I
NEXT I
OUTPUT Total // → 55
Trace the running total · ติดตามผลรวม
A FOR loop repeats a set number of times. Step through and watch Total grow. · ลูป FOR ทำซ้ำจำนวนครั้งที่กำหนด ให้เดินผ่านและดู Total ที่เพิ่มขึ้น
STEP changes the count
STEPsets how much the counter changes each pass.STEP -1counts down.
FOR I ← 5 TO 1 STEP -1
OUTPUT I // 5, 4, 3, 2, 1
NEXT I
Watch out
- Use
FORwhen you know how many times to repeat; useWHILEwhen you do not. - The counter (
I) andNEXT Imust use the same name.
Common mistakes
FOR I ← 1 TO N ... NEXT Irunsntimes, including both ends.- The counter changes automatically each turn.
Now you try
- Use
FOR ... NEXT. Type<-for←. - Press Check answer to test it.
Use a FOR loop to output the numbers 1 to 5, one per line. · ใช้ลูป FOR เพื่อแสดงตัวเลข 1 ถึง 5, อย่างละบรรทัด
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Use a FOR loop to add up 1 to 10, then output the total (it is 55). · ใช้ลูป FOR เพื่อรวมผลตั้งแต่ 1 ถึง 10, แล้วแสดงผลรวม (ซึ่งมีค่า 55)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Read an INTEGER N, then output N × 1, N × 2, N × 3 (one per line). For input 4, output 4, 8, 12. · อ่านค่า INTEGER และ N, แล้วแสดงผล N × 1, N × 2, N × 3 (หนึ่งบรรทัดต่อตัว) สำหรับอินพุต 4, ผลลัพธ์ที่ได้คือ 4, 8, 12
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่