Java For Loops
Master counter-controlled repetition in Java: learn the anatomy of a for loop, trace its execution step by step, and write loops that solve real problems.
Why Do We Need Repetition?
Imagine you want to print "Hello" ten times. Without a loop, you would copy-paste the same line ten times. With a for loop, you write the instruction once and let the computer repeat it for you.
Key Vocabulary
Anatomy of a For Loop
The Three Parts in Detail
Execution Flow
for vs. while
| for Loop | while Loop | |
|---|---|---|
| Best for | Known number of iterations | Unknown number of iterations |
| Counter location | Declared in header | Declared before the loop |
| Update location | In the header | Inside the body |
| Scope of variable | Limited to the loop | Available after the loop |
| Risk of infinite loop | Lower (all parts visible) | Higher (update may be forgotten) |
How to Write a For Loop
Example 1: Print 0 through 4
This loop prints the numbers 0, 1, 2, 3, 4: one per line. The variable i starts at 0, and the loop runs as long as \(i < 5\). After each iteration, i++ adds 1.
Example 2: Sum \(1\) to \(n\)
Here we use \(\le\) instead of \(<\) because we want to include the value \( n \). The accumulator variable sum is declared outside the loop so it retains its value after the loop ends.
Example 3: Counting Down
For loops can count downward. The initialization sets \( i = 10 \), the condition uses \(\ge\), and the update is i--. Output: 10, 9, 8, ... 2, 1, Liftoff!
Example 4: Custom Step Size
The update i += 2 increases the counter by 2 each iteration, printing only even numbers. You can use any integer step: i += 3, i += 10, or even i *= 2 for powers of two.
How Many Iterations?
Knowing exactly how many times a loop runs helps you predict output and avoid off-by-one errors. For a loop with step size 1:
Variable Scope
When you declare the loop variable inside the for header, it only exists within the loop. Trying to use it after the closing brace causes a compile-time error.
Common Mistakes
For Loop Quick Reference
| Pattern | Code | Iterations |
|---|---|---|
| Count up 0 to \( n-1 \) | for (int i = 0; i < n; i++) | \( n \) |
| Count up 1 to \( n \) | for (int i = 1; i <= n; i++) | \( n \) |
| Count down \( n \) to 1 | for (int i = n; i >= 1; i--) | \( n \) |
| Even numbers 0 to \( n \) | for (int i = 0; i <= n; i += 2) | \( \lfloor n/2 \rfloor + 1 \) |
Question 1 of 5
What is the output of the following code?
for (int i = 0; i < 3; i++) { System.out.print(i + " "); }
Question 2 of 5
How many times does this loop execute its body?
for (int i = 1; i <= 10; i++)
Question 3 of 5
Which loop correctly prints the numbers 5, 4, 3, 2, 1?
Question 4 of 5
What happens if you write for (int i = 0; i < 5; i++); followed by System.out.println(i);?
Question 5 of 5
What is the value of sum after this code runs?
int sum = 0; for (int i = 0; i < 6; i += 2) { sum += i; }