vòng lặp for
Đã giới thiệu| English | Ý nghĩa |
|---|---|
| for loop/fɔː luːp/ | vòng lặp for |
A loop with a counter built in
- A for loop 计数循环 packs three parts into one line:
for (int i = 0; i < 5; i++) { ... }- Initialization (
int i = 0), condition (i < 5), update (i++). - Use
forwhen you know how many times to repeat.
The three parts, in order
- Initialization runs once, before the loop starts.
- The condition is checked before each pass (like
while). - The update runs after each pass, then the condition is re-checked.
- So the flow is: init → (test → body → update) → (test → body → update) → …

The three parts of a for loop and the order they run
for and while are interchangeable
- Any
forloop can be rewritten as awhileloop, and vice versa. for (int i=0; i<5; i++) {B}equalsint i=0; while (i<5) {B; i++;}.foris tidier when the counter setup, test, and change belong together.- Choose whichever makes the loop's intent clearest.
Counting a known number of times
for (int i = 0; i < n; i++)runs the body exactlyntimes (i=0ton-1).- Change the bounds to count differently:
i = 1; i <= nrunsntimes too. - Watch the boundary:
<stops one before,<=includes the end. - This is the standard pattern for "do something
ntimes."
Mind the loop bounds — an off-by-one changes the count. for (int i = 0; i < n; i++) runs n times (i from 0 to n-1); switching to i <= n runs n+1 times and often overruns an array. Trace the first and last value of i to confirm the count before trusting a for loop.
Printing 0,1,2,3,4:
for (int i = 0; i < 5; i++) { System.out.println(i); }istarts0, runs whilei < 5,i++each pass.- Prints
0 1 2 3 4(five values); ati = 5the condition fails → stop.
A for loop combines initialization (once), a condition (checked before each pass), and an update (after each pass): for (int i = 0; i < n; i++) runs the body n times. It's interchangeable with a while loop. Mind the bounds — < vs <= changes the count by one.
Một vòng lặp for đếm từ 0 đến 4
i chạy từ 0..4 (năm lần lặp); tại i=5 điều kiện không thỏa mãn.
Ba phần của header vòng lặp for, theo thứ tự là...
Độ khó 1/5 · 100 xu + một phần thưởng nhỏ cho lần hoàn thành đầu tiên trong ngày
for (init; condition; update).
Thân của for (int i = 0; i < 5; i++) sẽ chạy bao nhiêu lần?
Độ khó 2/5 · 140 xu + một phần thưởng nhỏ cho lần hoàn thành đầu tiên trong ngày
i nhận các giá trị 0,1,2,3,4 → 5 lần lặp.
Phần khởi tạo của một vòng lặp for chạy...
Độ khó 1/5 · 100 xu + một phần thưởng nhỏ cho lần hoàn thành đầu tiên trong ngày
Init chạy một lần; condition được kiểm tra mỗi lần lặp; update chạy sau mỗi lần.
Bất kỳ vòng lặp for nào cũng có thể viết lại thành một vòng lặp while tương đương.
Độ khó 1/5 · 100 xu + một phần thưởng nhỏ cho lần hoàn thành đầu tiên trong ngày
for và while có thể hoán đổi cho nhau.
Vòng lặp for (int i = 1; i <= 5; i++) sẽ chạy bao nhiêu lần?
Độ khó 2/5 · 140 xu + một phần thưởng nhỏ cho lần hoàn thành đầu tiên trong ngày
i nhận 1..5 (bao gồm hai đầu) → 5 truyền đi.