Loops: while, for, and accumulation · 循环:while、for 和累加
Loops
- A loop repeats a block of code many times.
- Loops let you count, add up numbers, and do work without copying lines.
- In this lesson you learn the
whileloop and theforloop.
循环
- 循环(loop)会把一段代码重复执行很多次。
- 循环让你计数、累加数字,而不用复制粘贴一行行代码。
- 在这节课里,你学习
while循环和for循环。
The while loop
- A
whileloop runs its block again and again while a condition istrue. - You need three parts: start a counter, test it, and change it inside the loop.
- If you never change the counter, the loop runs forever. Be careful.
while 循环
while循环在条件为true时,一遍又一遍地运行它的代码块。- 你需要三个部分:初始化一个计数器、判断它,并在循环里改变它。
- 如果你从不改变计数器,循环就会永远运行。要小心。
public class Main {
public static void main(String[] args) {
int i = 1; // start
while (i <= 3) { // test
System.out.println("Line " + i);
i = i + 1; // change
}
}
}
The for loop
- A
forloop puts the start, test, and change on one line. - The shape is
for (start; test; change) { ... }. - It does the same job as the
whileabove, but it is shorter and clearer.
for 循环
for循环把初始化、判断和改变写在一行上。- 它的形式是
for (start; test; change) { ... }。 - 它做的事情和上面的
while一样,但更短、更清楚。
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
System.out.println("Line " + i);
}
}
}
Accumulation
- Accumulation means building up an answer step by step inside a loop.
- Use a variable that starts at
0and grows:sum = sum + i;. i++is a short way to writei = i + 1.sum += iis short forsum = sum + i.
累加
- 累加(accumulation)是指在循环里一步一步地构建出一个答案。
- 用一个从
0开始并不断增长的变量:sum = sum + i;。 i++是i = i + 1的简写。sum += i是sum = sum + i的简写。
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i; // add each number
}
System.out.println(sum); // 15
}
}
Counting with a condition
- You can count how many times something is true.
- Start a counter at
0, and add1only when the test passes. - Here we count even numbers from 1 to 10.
带条件的计数
- 你可以数一数某件事发生了多少次。
- 让一个计数器从
0开始,只在判断通过时加1。 - 这里我们数从 1 到 10 的偶数。
public class Main {
public static void main(String[] args) {
int count = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) { // % gives the remainder
count++;
}
}
System.out.println(count); // 5
}
}
Off-by-one care
- The most common loop bug is doing one too many or one too few steps.
i <= nincludesn.i < nstops beforen.- To loop from 1 to
n(and includen), usefor (int i = 1; i <= n; i++).
小心差一错误
- 最常见的循环错误就是多做了一次或少做了一次。
i <= n包含n。i < n在n之前就停止。- 要从 1 循环到
n(并且包含n),用for (int i = 1; i <= n; i++)。
public class Main {
public static void main(String[] args) {
int n = 4;
// i goes 1, 2, 3, 4 — four times, because of <=
for (int i = 1; i <= n; i++) {
System.out.println(i);
}
}
}
Common mistakes
for (int i = 0; i < n; i++)runsntimes;<=runs one extra.- Do not put a
;right afterfor(...).
常见错误
for (int i = 0; i < n; i++)运行n次;用<=会多跑一次。- 不要在
for(...)后紧跟;。
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- Press Run to compile and run, then Check answer.
- Your code compiles and runs on the server, so even the first run is fast.
现在轮到你
- 每个任务都已经填好了类的骨架 —— 把你的代码写在 main 里面,或者补全给出的方法。
- 按运行来编译并运行,然后按检查答案。
- 你的代码在服务器上编译并运行,所以第一次运行也很快。
Loops and accumulation · 循环与累加
A loop repeats; an accumulator builds up across the passes. · 循环重复执行;累加器在每轮中逐步累积。
Use a for loop to print the numbers 1 to · 到 5, each on its own line. · 用一个 for 循环打印数字 1 到 5,每个数字单独占一行。
Click Run to see the output here. · 点击“运行”查看此处输出。
Complete sumTo(int n) so it returns the sum 1 + 2 + ... + n. For example sumTo(5) is 15. If n is 0 or less, return 0. · 完成 sumTo(int n),让它返回和 1 + 2 + ... + n。例如 sumTo(5) 是 15。如果 n 小于或等于 0,返回 0。
Click Run to see the output here. · 点击“运行”查看此处输出。
Complete countMultiples(int n, int k) so it returns how many numbers from 1 to · 到 n divide evenly by k (use % == 0). For example countMultiples(10, 3) is 3 (that is 3, 6, 9). · 完成 countMultiples(int n, int k),让它返回从 1 到 n 中能被 k 整除的数字有多少个(用 % == 0)。例如 countMultiples(10, 3) 是 3(也就是 3、6、9)。
Click Run to see the output here. · 点击“运行”查看此处输出。