for Loops
| English | Chinese | Pinyin |
|---|---|---|
| for loop | 计数循环 | jì shù xún huán |
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) → …
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.
A for loop counting 0 to 4
i runs 0..4 (five passes); at i=5 the condition fails.
The three parts of a for-loop header are, in order...
for (init; condition; update).
How many times does the body of for (int i = 0; i < 5; i++) run?
i takes 0,1,2,3,4 → 5 passes.
The initialization part of a for loop runs...
Init runs once; condition is checked each pass; update runs after each.
Any for loop can be rewritten as an equivalent while loop.
for and while are interchangeable.
How many times does for (int i = 1; i <= 5; i++) run?
i takes 1..5 (inclusive) → 5 passes.