2.8 for loopsCounting loops on one line

A for loop header has three parts, separated by semicolons: for (initialization; condition; update). The initialization runs once, before anything else. The condition is checked before every pass, exactly like a while loop. The update runs after every pass, and then the condition is checked again.
A variable declared in the initialization, like int i, exists only inside the loop. After the loop ends, using i doesn't compile. If you need the final value, declare the variable before the loop.
Every for loop can be rewritten as a while loop with the same three parts: put the initialization before the loop, the condition in the while, and the update at the end of the body. for (int i = 0; i < n; i++) { ... } is int i = 0; while (i < n) { ...; i++; }. The two run exactly the same passes.
?Wait, what does i++ do?
1for (int i = 1; i <= 5; i++)12{3 System.out.print(i * i + " ");4}5System.out.println();6for (int k = 10; k > 0; k -= 3)27{8 System.out.print(k + " ");9}10System.out.println();
- line 1 <= includes 5: five passes
- line 6 Counting down by 3: 10, 7, 4, 1, then -2 fails
Counting passes without tracing is a skill the exam rewards. for (int i = a; i < b; i++) runs b - a times. With <=, for (int i = a; i <= b; i++) runs b - a + 1 times. For other steps, list the values: for (int i = 3; i < 20; i += 4) uses 3, 7, 11, 15 and 19, so it runs 5 times.
?Wait, why b - a and not b - a + 1?
I thought about it. Show me
What is printed?
int sum = 0;
int passes = 0;
for (int k = 10; k > 0; k -= 3)
{
sum += k;
passes++;
}
System.out.println(sum + " " + passes);- Initialization: k is 10. 10 > 0, so pass 1: sum is 10, passes is 1. Update: k is 7.
- 7 > 0: pass 2, sum is 17, passes is 2. k is 4. 4 > 0: pass 3, sum is 21, passes is 3. k is 1.
- 1 > 0: pass 4, sum is 22, passes is 4. k is -2. -2 > 0 is false, so the loop ends.
Why?
The update always runs after the last pass, and then the condition fails. That's why the loop variable ends one step past the last value used. - It prints 22 4.
Answer: 22 4
Stuck? Get a hint
- List the values k takes: start at 10, subtract 3 each time.
- 10, 7, 4, 1. Is -2 > 0?
- Add the four values for sum, and count them for passes.
- Afor (int i = 1; i < 10; i++)
- Bfor (int i = 0; i <= 10; i++)
- Cfor (int i = 1; i <= 10; i++)
- Dfor (int i = 0; i < 10; i++)
Show the answer
C. Starting at 1 and stopping after 10 needs i <= 10 (10 passes). Choice A stops at 9. Choice B starts at 0, printing 11 numbers. Choice D runs 10 times, but prints 0 through 9 unless you print i + 1. Off-by-one errors live in exactly these differences.
- for (init; condition; update): init once, condition before every pass, update after every pass.
- for (int i = a; i < b; i++) runs b - a times; with <=, b - a + 1 times.
- A variable declared in the header doesn't exist after the loop.
- Any for loop can be rewritten as a while loop with the same three parts.