Iteration: FOR
Cambridge Pseudocode Lesson 7 2:08 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Iteration is the third control structure, and a FOR loop is the version you use when you already know how many times.
循环是第三种控制结构, 而 FOR 循环是你已经知道要重复多少次时用的那一种。
It has exactly one moving part: the counter.
它恰好只有一个会动的部分:计数器。
You never change it yourself — the loop does.
你从来不自己改动它——是循环在改。
One, then two, three, four, five.
1,然后 2、3、4、5。
Then it stops, because five was the end value, and note that both ends are included: one TO five is five passes, not four.
然后它停下,因为 5 是终值, 并且注意两端都包含在内:1 TO 5 是 5 趟,不是 4 趟。
Totalling is the standard method the exam asks for most, and it needs a second variable.
求和是考卷最常考的标准方法,而它需要第二个变量。
Set the total to nought BEFORE the loop — forget that line and your answer is whatever was left in memory.
在循环之前把总和设为 0—— 忘了那一行,你的答案就是内存里恰好剩下的东西。
Then watch them both: the counter goes up by one, and the total goes up by the counter.
然后同时看这两个:计数器每次加 1,而总和每次加上计数器。
After ten passes it is fifty-five.
跑完 10 趟之后,它是 55。
By default the counter moves up by one, and STEP changes that.
默认情况下计数器每次加 1,而 STEP 改变这一点。
STEP minus one counts down, so five TO one gives five, four, three, two, one — and note that the start is the bigger number now.
STEP -1 是倒数,所以 5 TO 1 给出 5、4、3、2、1—— 并且注意现在起点是较大的那个数。
STEP two counts in twos.
STEP 2 就是每次跳 2。
If the STEP would never reach the end value, the loop simply does not run.
如果这个步长永远走不到终值,那这个循环干脆一次都不跑。
One decision decides the mark on a lot of questions.
一个判断决定了很多题目的得分。
Use FOR when the number of repeats is known in advance: ten squares, thirty marks in an array.
当重复次数事先已知时用 FOR:前 10 个平方数,数组里的 30 个分数。
Do not use it when you cannot know — keep asking until they type QUIT, or read a file until it ends.
当你无法知道时就别用它—— 一直问到用户输入 QUIT 为止,或者读一个文件直到它结束。
Those need the loops in lesson eight.
那些需要第 8 课的循环。
If the count is fixed before the loop starts, it is a FOR.
如果次数在循环开始之前就已经确定,那就是 FOR。
Four things to take with you.
带走四点。
One: FOR counts from a start value to an end value.
第一:FOR 从起始值数到结束值。
Two: both ends are included, so one TO five runs five times.
第二:两端都包含,所以 1 TO 5 会跑 5 次。
Three: STEP changes the size of each move.
第三:STEP 改变每一步的大小。
Four: NEXT must name the same counter.
第四:NEXT 后面必须写同一个计数器的名字。
Now do the three tasks.
现在去做那三道题。