Skip to content

Nested loops

C Programming Lesson 6 1:54 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
A loop inside a loop is not complicated, but the order matters and it is easy to get backwards. 循环里套循环并不复杂,但顺序很重要,而且很容易搞反。
The outer counter takes one value. 外层计数器取一个值。
Then the inner loop runs all the way through, from its start to its finish. 然后内层循环从头到尾完整跑一遍。
Only then does the outer counter move on, and the inner loop starts again from the beginning. 跑完之后,外层计数器才往前走一步,内层循环又从头开始。
Three outer values with three inner values each is nine passes in all — the counts multiply. 三个外层值,每个配三个内层值,一共是九轮——次数是相乘的。
Now watch it print. 现在看它打印的过程。
On the first outer pass, three stars appear side by side, because the inner loop prints three of them without a newline between. 外层第一轮时,三颗星并排出现, 因为内层循环打印了三颗,中间没有换行。
Then the newline runs, and the second row starts underneath. 然后换行执行,第二行从下面开始。
That is where the rows come from — and notice where that newline sits: in the outer loop, not the inner one. 行就是这么来的—— 而且注意那个换行在哪里:在外层循环里,不在内层。
Put it inside and you get one star per line instead of a block. 放到里面去,你得到的就是每行一颗星,而不是一个方块。
Now the lesson's second task: a triangle instead of a block. 现在做课程里的第二道题:把方块换成三角形。
Row one has one star, row two gets two, row three gets three, and so on. 第一行一颗星,第二行两颗,第三行三颗,以此类推。
Look at what changed in the code — only the inner loop's limit. 看看代码里改了什么——只有内层循环的上限。
Instead of a fixed three, it runs up to r, so the length of each row depends on the outer counter. 不再是固定的 3,而是一直到 r,所以每一行的长度取决于外层计数器。
One character different, and a square becomes a triangle. 改一个字符,正方形就变成了三角形。
Four things to take with you. 带走四点。
One: the outer loop picks the row. 第一:外层循环决定是哪一行。
Two: the inner loop walks that row completely before the outer one moves. 第二:内层循环把那一行完整走完,外层才往前走。
Three: the newline belongs to the outer loop — that is what ends a row. 第三:换行属于外层循环——正是它结束一行。
Four: the total number of passes is rows times columns, so the counts multiply. 第四:总轮数是行数乘以列数,次数是相乘的。
Now do the three tasks; the last one counts pairs. 现在去做那三道题;最后一题是数出有多少对。

Log in or create account

IGCSE, A-Level & AP