Loops in C
C Programming Lesson 4 2:10 English narration · English + 中文 subtitles burned in
Chapters
Transcript
C gives you two loops, and for counting they do the same job.
C 给了你两种循环,用来计数时它们做的是同一件事。
The while version puts the start, the test and the step in three separate places, and the day you forget the step it runs forever.
while 的写法把初始化、判断和步进放在三个不同的地方, 哪天你忘了写步进,它就会永远跑下去。
The for version gathers all three into one header, where they are hard to lose.
for 的写法把这三样都收进一个头部,很难漏掉。
So: use for when you are counting, and reach for while when the finish depends on something else — a reading, an input, a search that has not succeeded yet.
所以:计数时用 for;当结束条件取决于别的东西时用 while—— 比如一个读数、一次输入,或者一次还没成功的查找。
Two patterns live inside almost every loop you will write, and they look nearly identical.
几乎你写的每一个循环里,都住着这两个模式,而且它们看起来几乎一样。
To accumulate, you start a total at zero and each pass adds the value: total plus-equals i.
要累加,就让 total 从 0 开始,每一轮把值加上去:total += i。
To count, you start a counter at zero and each pass adds one — but only when a test passes.
要计数,就让计数器从 0 开始,每一轮加 1——但只在判断通过时才加。
Same skeleton, one line different, and that one line is the whole difference between a total and a tally.
同样的骨架,只差一行,而这一行就是“总和”和“个数”之间的全部区别。
Now the lesson's second task: add up every number from one to n.
现在做课程里的第二道题:把 1 到 n 的所有数加起来。
It is the accumulate pattern exactly — total declared before the loop, added to inside, returned after.
这正是累加模式——total 在循环之前声明,在里面累加,在之后返回。
Five gives fifteen.
5 得到 15。
One gives one, the smallest ordinary case.
1 得到 1,这是最小的普通情况。
And zero?
那 0 呢?
The task says return zero, and you need no extra line for it: with n at zero the test fails immediately, the loop runs zero times, and the total is still what you started it at.
题目要求返回 0,而你不需要为它多写一行: n 为 0 时判断立刻失败,循环一次都不执行,total 还是你给它的初始值。
Four things to take with you.
带走四点。
One: a for header gathers start, test and step in one place, which is why it is safer for counting.
第一:for 的头部把初始化、判断和步进收在一个地方, 所以用来计数更安全。
Two: to accumulate, write total plus-equals the value.
第二:要累加,就写 total += 那个值。
Three: to count, write count plus plus inside an if.
第三:要计数,就在 if 里面写 count++。
Four: always check the empty case — and notice how often a well-written loop already handles it.
第四:永远检查一下空的情况——你会发现,写得好的循环常常已经处理好了。
Now do the three tasks; the last one counts multiples.
现在去做那三道题;最后一题是数出有多少个倍数。