Iteration: WHILE and REPEAT · 迭代:WHILE 与 REPEAT
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
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循环在每一轮之前检查它的测试。- 如果一开始测试就为假,循环体运行零次。
- 代码块以
ENDWHILE结束。
Count ← 1
WHILE Count <= 3 DO
OUTPUT Count // 1, 2, 3
Count ← Count + 1
ENDWHILE
English
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
Explore · 探索
REPEAT runs, then tests · REPEAT 先运行,再测试
WHILE tests before · 在...之前 (may run 0 times); REPEAT tests after · 之后 (runs at least once). · WHILE 在之前测试(可能 0 次);REPEAT 在之后测试(至少 1 次)。
English
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 次。
English
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后测,所以至少运行一次。- 在里面改动某个值,否则循环永不结束。
English
Now you try
- Pick
WHILEorREPEATfor each task. - Press Check answer to test it.
中文
现在轮到你
- 为每个任务选择
WHILE或REPEAT。 - 按检查答案来测试它。
Use a WHILE loop to output 1, 2, 3, one per line. · 用 WHILE 循环输出 1、2、3,每行一个。
Click Run to see the output here. · 点击“运行”查看此处输出。
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. · 点击“运行”查看此处输出。
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. · 点击“运行”查看此处输出。