01 / 21

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.

Java

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.

Without a Loop
10 identical lines of code: error-prone, tedious, and hard to change.
With a For Loop
3 lines total: concise, easy to modify, and scales to any count.

Key Vocabulary

Iteration
One complete execution of the loop body.
Loop Variable
The counter that tracks which iteration you are on (often named i).
Loop Body
The block of code inside the braces { } that repeats each iteration.

Anatomy of a For Loop

for ( int i = 0 ;
\(\textcolor{#e06c75}{i}\ \textcolor{#abb2bf}{<}\ \textcolor{#d19a66}{5}\)
; i ++ ) Initialization Runs once at start Condition Checked before each iteration Update Runs after each iteration // The loop body goes inside { ... }

The Three Parts in Detail

1
Initialization (int i = 0): declares and sets the loop variable to its starting value. Runs exactly once.
2
Condition (\(i < 5\)): a boolean expression evaluated before each iteration. If true, the body executes; if false, the loop ends.
3
Update (i++): modifies the loop variable after each iteration of the body, moving the counter toward the termination condition.

Execution Flow

int i = 0
\(i < 5\)?
true loop body { } i++ false End

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

1
Identify the range: what is the start value and the end value of the counter?
2
Write the initialization: declare the loop variable at the start value: int i = start.
3
Set the condition: choose \(<\), \(\le\), \(>\), or \(\ge\) so the loop runs the right number of times.
4
Choose the update: i++ to count up by 1, i-- to count down, or i += step for other increments.
5
Write the body: place the repeated work inside the curly braces { }.

Example 1: Print 0 through 4

for (int i = 0; i < 5; i++) { System.out.println(i); }

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\)

int n = 100; int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } // sum is now 5050

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 (int i = 10; i >= 1; i--) { System.out.println(i); } System.out.println("Liftoff!");

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

// Print even numbers from 0 to 20 for (int i = 0; i <= 20; i += 2) { System.out.print(i + " "); } // Output: 0 2 4 6 8 10 12 14 16 18 20

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.

i++
Step by 1 (most common)
i += k
Step by any constant \( k \)
i *= 2
Double each time (exponential)

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:

\(i < 5\) starting at 0
\( 5 - 0 = 5 \) iterations: values 0, 1, 2, 3, 4
\(i \le 5\) starting at 1
\( 5 - 1 + 1 = 5 \) iterations: values 1, 2, 3, 4, 5

Variable Scope

for (int i = 0; i < 3; i++) { System.out.println(i); // OK } System.out.println(i); // ERROR: i is not defined here

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

✕ Off-By-One
Using \(<\) when you need \(\le\) (or vice versa), causing one too many or too few iterations.
✕ Infinite Loop
Forgetting the update or updating in the wrong direction, so the condition is never false.
✕ Semicolon After Header
Writing for (...) ; puts an empty body: the real body runs only once, not in the loop.

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; }