Loops: while, for, and accumulation · 循环:while、for 与累加
Repeating work
- A loop runs the same block of code many times, so you don't copy it by hand.
- C has three loops:
while,for, anddo-while. They all repeat while a condition is true. - The condition is checked each time around. When it becomes false, the loop stops.
重复做事
- 循环让同一段代码运行很多次,这样你就不用手动复制它。
- C 有三种循环:
while、for、do-while。它们都在条件为真时重复。 - 每一轮都会检查条件。当条件变为假时,循环就停止。
while loops
while (test) { ... }checks the test first, then runs the block if it is true.- Something inside the block must eventually make the test false, or the loop never ends.
- Use
whilewhen you don't know in advance how many times you will repeat.
while 循环
while (判断) { ... }先检查判断,如果为真就运行代码块。- 代码块里必须有东西最终让判断变为假,否则循环永远不会结束。
- 当你事先不知道要重复多少次时,用
while。
for loops
- A
forloop puts three parts in one line:for (start; test; step). for (int i = 0; i < 5; i++)means: startiat0, keep going whilei < 5, add1each time.- Use
forwhen you are counting a known number of times.
for 循环
for循环把三个部分放在一行:for (起始; 判断; 步进)。for (int i = 0; i < 5; i++)表示:让i从0开始,只要i < 5就继续,每次加1。- 当你要数已知的次数时,用
for。
#include <stdio.h>
int main(void) {
int total = 0;
for (int i = 1; i <= 4; i++) {
total = total + i; // accumulate: 1, then 3, then 6, then 10
}
printf("%d\n", total); // 10
return 0;
}
Accumulation and counting
- An accumulator is a variable that builds up a result across the loop, like
totalabove. - A counter adds
1each time something happens, to count matches. break;stops the loop early;continue;skips to the next round.
累加与计数
- 累加器是一个变量,在循环过程中一点点积累出结果,就像上面的
total。 - 计数器在每次发生某事时加
1,用来计数。 break;提前结束循环;continue;跳到下一轮。
Common mistakes
- Do not put a
;right afterfor(...)— it makes an empty loop. - Change the condition so the loop can end.
常见错误
- 不要在
for(...)后紧跟;——那会得到空循环。 - 改动条件,让循环能结束。
Now you try
- Set up your accumulator or counter before the loop, update it inside, and use it after.
- For the function tasks, do not write a
main— the checker provides one.
现在轮到你了
- 在循环之前建立累加器或计数器,在循环里面更新它,在循环之后使用它。
- 函数任务里,不要自己写
main—— 检查器会提供。
Loops and accumulation · 循环与累加
A loop repeats; a running total · 累加总和 builds up each pass. · 循环重复执行;累加的总和每轮增长。
In main, use a for loop to print the numbers 1 to · 到 5, each on its own line. · 在 main 里面,用一个 for 循环打印数字 1 到 5,每个数字单独占一行。
Click Run to see the output here. · 点击“运行”查看此处输出。
Complete int sum_to(int n) so it returns 1 + 2 + ... + n. Return 0 when n is 0 or negative. Do not · 不 write a main. · 完成 int sum_to(int n),让它返回 1 + 2 + ... + n。当 n 为 0 或负数时返回 0。不要写 main。
Click Run to see the output here. · 点击“运行”查看此处输出。
Complete int count_multiples(int n, int k) so it returns how many numbers from 1 to · 到 n are divisible by k. Use % inside a loop. Do not · 不 write a main. · 完成 int count_multiples(int n, int k),让它返回从 1 到 n 里能被 k 整除的数有多少个。在循环里用 %。不要写 main。
Click Run to see the output here. · 点击“运行”查看此处输出。