Iteration: WHILE and REPEAT
Cambridge Pseudocode Lesson 8 2:11 English narration · English + 中文 subtitles burned in
Chapters
Transcript
When you do not know how many repeats you need, the test moves into the loop itself.
当你不知道需要重复多少次时,测试就搬进循环本身里面。
In a WHILE loop the test is at the top: it is checked before you are let in, and again before every later pass.
在 WHILE 循环里,测试在顶部: 进去之前先检查一次,之后每一趟之前再检查一次。
Count starts at one, and while it is three or less the body runs — one, two, three — and then the test fails and the loop ends.
Count 从 1 开始,只要它小于等于 3,循环体就运行—— 1、2、3——然后测试不成立,循环结束。
The block is closed by ENDWHILE.
这一段由 ENDWHILE 关闭。
A REPEAT loop puts the test at the bottom instead.
REPEAT 循环把测试放在底部。
You go in first and are asked afterwards whether to go round again.
你先进去,之后才被问要不要再来一趟。
N starts at nought, gains two each pass — two, four, six — and after the pass that reaches six the test finally holds and it stops.
N 从 0 开始,每趟加 2——2、4、6—— 在到达 6 的那一趟之后,测试终于成立,它停下来。
Notice the closing word: UNTIL, not ENDREPEAT, and the condition after it is the one that ENDS the loop.
注意收尾的那个词:是 UNTIL,不是 ENDREPEAT, 而它后面的条件是那个"结束"循环的条件。
Now the case that separates them.
现在来看把它们分开的那种情形。
Start with the condition already settled before the loop runs.
让条件在循环开始之前就已经定了。
The WHILE tests first, fails first, and prints nothing at all — zero passes.
WHILE 先测试,先失败,于是什么都不打印——0 趟。
The REPEAT is already inside when it asks, so it does one pass anyway and prints nine.
REPEAT 在发问的时候人已经在里面了, 所以它无论如何跑了一趟,打印出 9。
That is the whole difference, and it is what an exam question comparing the two is really asking.
这就是全部的区别, 也是一道比较这两者的考题真正在问的东西。
One more thing, and it is the bug you will actually write.
还有一件事,而它是你真的会写出来的那个 bug。
Neither loop has a counter that moves by itself, so something inside the body must push the test toward stopping.
这两种循环都没有一个会自己走的计数器, 所以循环体里必须有东西把测试往"停止"的方向推。
Take that one line back out and Count stays at one forever — the condition can never fail, and the program hangs.
把那一行拿掉,Count 就永远停在 1—— 条件永远不会不成立,程序就卡死了。
Four things to take with you.
带走四点。
One: WHILE tests before each pass and ends at ENDWHILE.
第一:WHILE 在每一趟之前测试,以 ENDWHILE 结束。
Two: REPEAT tests after each pass and ends at UNTIL.
第二:REPEAT 在每一趟之后测试,以 UNTIL 结束。
Three: so a WHILE may run zero times, and a REPEAT runs at least once.
第三:所以 WHILE 可能一次都不跑,而 REPEAT 至少跑一次。
Four: change something inside, or the loop never ends.
第四:在里面改变点什么,否则循环永远不会结束。
Now do the three tasks.
现在去做那三道题。