Iteration: FOR · 迭代:FOR
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
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
Explore · 探索
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. · 点击“运行”查看此处输出。
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. · 点击“运行”查看此处输出。
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. · 点击“运行”查看此处输出。