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 至最新版本。
English
FOR counts
- A count-controlled loop runs once for each integer from the start to the end, inclusive.
- The counter is an
INTEGER. - It is good practice to repeat the counter's name after
NEXT.
中文
FOR 用来计数
- 计数循环对从起点到终点的每个整数运行一次,两端都包括。
- 计数器是
INTEGER。 - 在
NEXT后面再写一次计数器的名字,是好的写法。
DECLARE Total : INTEGER
Total ← 0
FOR I ← 1 TO 5
Total ← Total + I
NEXT I
OUTPUT Total
Explore · 探索
Trace the running total · 追踪累积的总和
A FOR loop repeats a set number of times. Step through and watch Total grow. · FOR 循环重复固定的次数。一步步走,看着 Total 增长。
English
STEP changes the jump
STEPsets the gap between values. It can be negative.- If the start is already past the end in the step's direction, the body does not run.
中文
STEP 改变步长
STEP设定相邻两个值的间隔。它可以是负数。- 如果起点在步长的方向上已经越过终点,循环体不会运行。
FOR I ← 5 TO 1 STEP -2
OUTPUT I
NEXT I
English
Watch out
NEXT Imust name the counter of this loop.- The body is indented.
NEXTlines up withFOR.
中文
注意
NEXT I必须写出这个循环的计数器。- 循环体要缩进。
NEXT和FOR对齐。
English
Common mistakes
1 TO 5includes both 1 and 5.- Do not change the counter yourself inside the body.
中文
常见错误
1 TO 5包括 1 和 5。- 不要在循环体里自己去改计数器。
English
Now you try
- Use a
FORloop to print a run of numbers.
中文
现在你来试
- 用
FOR循环打印一串数字。
Use a FOR loop to output the numbers 1 to · 到 5, one per line. · 用 FOR 循环输出数字 1 到 5,每行一个。
Click Run to see the output here. · 点击“运行”查看此处输出。
Output · 输出 5, 3 and 1, using FOR with STEP -2. · 用带 STEP -2 的 FOR 输出 5、3 和 1。
Click Run to see the output here. · 点击“运行”查看此处输出。