Iteration: FOR
此页面需较新浏览器(支持 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.
English
DECLARE Total : INTEGER
DECLARE I : INTEGER
Total ← 0
FOR I ← 1 TO 5
Total ← Total + I
NEXT I
OUTPUT Total
探索
Trace the running total
A FOR loop repeats a set number of times. Step through and watch Total grow.
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.
English
DECLARE Minute : INTEGER
FOR Minute ← 0 TO 60 STEP 15
OUTPUT Minute, " minutes"
NEXT Minute
- A negative
STEPcounts down:FOR Floor ← 10 TO 0 STEP -5gives 10, 5, then 0.
English
Watch out
NEXT Imust name the counter of this loop.- The body is indented.
NEXTlines up withFOR.
English
Common mistakes
Before a loop, distinguish DECLARE Count : INTEGER (choose a type) from Count ← 0 (store a value). The loop header changes the counter; the body changes the result you are computing.
1 TO 5includes both 1 and 5.- Do not change the counter yourself inside the body.
English
Now you try
- Use a
FORloop to print a run of numbers.
English
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 金币及少量额外奖励
Use a FOR loop to output the numbers 1 到 5, one per line.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
输出 5, 3 and 1, using FOR with STEP -2.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Read UpperLimit (1 to 10). Output the sum of the squares of integers from 1 to UpperLimit inclusive.
点击“运行”查看此处输出。