Loops: while, for, and accumulation · Vòng lặp: while, for, và tích lũy
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.
Vòng lặp
- Một vòng lặp lặp lại một khối mã nhiều lần.
- Vòng lặp giúp bạn đếm, cộng tổng các số và thực hiện công việc mà không cần sao chép dòng code.
- Trong bài học này, bạn sẽ học về vòng lặp
whilevà vòng lặpfor.
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.
Vòng lặp while
- Một vòng lặp
whilechạy khối mã của nó lặp đi lặp lại trong khi điều kiện làtrue. - Bạn cần ba phần: bắt đầu một bộ đếm, kiểm tra nó, và thay đổi nó bên trong vòng lặp.
- Nếu bạn không bao giờ thay đổi bộ đếm, vòng lặp sẽ chạy mãi mãi. Hãy cẩn thận.
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.
Vòng lặp for
- Một vòng lặp
forđặt bắt đầu, kiểm tra và thay đổi trên một dòng. - Cấu trúc của nó là
for (start; test; change) { ... }. - Nó làm cùng một việc như
whileở trên, nhưng ngắn gọn và rõ ràng hơn.
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.
Tích lũy
- Tích lũy có nghĩa là xây dựng dần đáp án từng bước bên trong vòng lặp.
- Sử dụng một biến bắt đầu từ
0và tăng dần:sum = sum + i;. i++là cách viết tắt củai = i + 1.sum += ilà viết tắt củasum = 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.
Đếm với điều kiện
- Bạn có thể đếm xem một sự kiện đúng bao nhiêu lần.
- Bắt đầu bộ đếm ở
0, và thêm1chỉ khi phép kiểm tra đạt yêu cầu. - Ở đây chúng ta đếm các số chẵn từ 1 đến 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++).
Cẩn thận sai lệch một bước
- Lỗi loop phổ biến nhất là thực hiện quá một hoặc thiếu một bước.
i <= nbao gồmn.i < ndừng lại trướcn.- Để lặp từ 1 đến
n(bao gồm cản), hãy dùngfor (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(...).
Lỗi thường gặp
for (int i = 0; i < n; i++)chạynlần;<=chạy thêm một lần nữa.- Đừng để một
;ngay saufor(...).
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.
Bây giờ bạn thử
- Mỗi nhiệm vụ điền sẵn khung lớp — viết mã của bạn bên trong main, hoặc hoàn thành phương thức được hiển thị.
- Nhấn Chạy để biên dịch và chạy, sau đó Kiểm tra câu trả lời.
- Mã của bạn được biên dịch và chạy trên máy chủ, vì vậy ngay cả lần chạy đầu tiên cũng rất nhanh.
Loops and accumulation · Vòng lặp và tích lũy
A loop repeats; an accumulator builds up across the passes. · Một vòng lặp lặp lại; một biến tích lũy xây dựng giá trị qua các lần lặp.
Use a for loop to print the numbers 1 to 5, each on its own line. · Sử dụng vòng lặp ⟨for⟩ để in các số từ ⟨1⟩ đến ⟨5⟩, mỗi số trên một dòng riêng.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
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. · Hoàn thiện ⟨sumTo(int n)⟩ sao cho trả về tổng ⟨1 + 2 + ... + n⟩. Ví dụ ⟨sumTo(5)⟩ là ⟨15⟩. Nếu ⟨n⟩ là ⟨0⟩ hoặc nhỏ hơn, trả về ⟨0⟩.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
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). · Hoàn thiện ⟨countMultiples(int n, int k)⟩ sao cho trả về số lượng các số từ ⟨1⟩ đến ⟨n⟩ chia hết cho ⟨k⟩ (sử dụng ⟨% == 0⟩). Ví dụ ⟨countMultiples(10, 3)⟩ là ⟨3⟩ (tức là 3, 6, 9).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.