01 / 21

Java for Loops

Master the most fundamental iteration construct in Java: control flow with initialization, condition, and update in a single, powerful statement.

AP Computer Science A

What Is a Loop?

A loop is a control structure that repeats a block of code multiple times. Instead of writing the same statement over and over, a loop lets you automate repetition with just a few lines.

Start Condition true? yes Loop Body repeat no: exit

Why Use a for Loop?

A for loop is ideal when you know in advance how many times the code should repeat. It bundles three parts into one clean header: initialization, condition, and update.

Counting
Iterate from \( 0 \) to \( n - 1 \) to process each element.
Accumulating
Sum values, build strings, or aggregate results step by step.
Searching
Scan through data to find a target value or compute a maximum.

Anatomy of a for Loop

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}
Initialization
int i = 0 — runs once before the loop starts.
Condition
i < 5 — checked before each iteration. Loop continues while true.
Update
i++ — executes after each iteration of the body.

Execution Flow

1. Initialize i = 0
2. Check \( i < 5 \text{ ?} \)
true 3. Execute Body 4. Update i++ repeat false Exit Loop

The Three Parts in Detail

1
Initialization: declares and sets the loop variable. Runs exactly once. The variable's scope is limited to the loop.
2
Boolean condition: evaluated before each iteration. Must be a boolean expression. When false, the loop terminates.
3
Update: modifies the loop variable after each pass. Common forms: i++, i--, i += 2.

for vs while

for Loop while Loop
Best when Number of iterations is known Number of iterations is unknown
Structure Init, condition, update in one line Condition only; init/update are separate
Variable scope Loop variable is local to the loop Variable must be declared outside
Risk of infinite loop Lower: update is built-in Higher: easy to forget update
Example use Traverse an array by index Read input until sentinel value

How to Write a for Loop

1
Identify the range: What is the starting value? What is the stopping value? How do you step through?
2
Write the header: for (int i = start; i < stop; i += step)
3
Write the body: Place the repeated action inside braces { }.
4
Trace the values: Mentally step through \( i = 0, 1, 2, \ldots \) to verify the output.
5
Check boundaries: Does the loop run the correct number of times? Watch for off-by-one errors.

Example 1: Print Numbers

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

Example 2: Sum from 1 to \( n \)

int n = 5;
int sum = 0;
for (int i = 1; i <= n; i++) {
    sum += i;
}
System.out.println(sum); // 15
Trace: i = 1 sum = 0+1 = 1 i = 2 sum = 1+2 = 3 i = 3 sum = 3+3 = 6 i = 4 sum = 6+4 = 10 i = 5 sum = 10+5 = 15

Example 3: Counting Backwards

for (int i = 5; i >= 1; i--) {
    System.out.print(i + " ");
}
// Output: 5 4 3 2 1
i = 5 5 i = 4 4 i = 3 3 i = 2 2 i = 1 1

Nested for Loops

for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 4; col++) {
        System.out.print("* ");
    }
    System.out.println();
}
Output: row=1: * * * * row=2: * * * * row=3: * * * *

How Many Iterations?

For a standard loop for (int i = a; i < b; i++), the number of iterations is:

Loop Header Iterations Values of i
i = 0; i < 5 5 0, 1, 2, 3, 4
i = 1; i <= 5 5 1, 2, 3, 4, 5
i = 3; i < 10 7 3, 4, 5, 6, 7, 8, 9
i = 0; i < n \( n \) 0, 1, ..., \( n - 1 \)

Traversing an Array

int[] scores = {85, 92, 78, 95, 88};
for (int i = 0; i < scores.length; i++) {
    System.out.println("Score " + i + ": " + scores[i]);
}
index: value: 0 85 1 92 2 78 3 95 4 88 scores.length = 5 → i goes from 0 to 4

Common Mistakes

Off-by-One Error
Using <= when you mean < (or vice versa), causing one too many or too few iterations.
Infinite Loop
Forgetting to change the loop variable, or updating it in the wrong direction (e.g., i++ when counting down).
Out-of-Bounds Access
Using i <= arr.length instead of i < arr.length, which accesses an index that does not exist.

Summary Table

Concept Key Point
Structure for (init; condition; update) { body }
Initialization Runs once; declares the loop variable
Condition Checked before each iteration; must be boolean
Update Runs after each iteration (e.g., i++)
Iteration count \( b - a \) for i = a; i < b
Array traversal Use i < array.length
Nested loops Inner loop completes fully per outer iteration

Question 1 of 5

What is the output of the following code?

for (int i = 1; i <= 3; i++) {
    System.out.print(i * 2 + " ");
}

Question 2 of 5

How many times does the following loop execute its body?

for (int k = 0; k < 10; k += 3) {
    System.out.println(k);
}

Question 3 of 5

What is the value of result after the loop?

int result = 1;
for (int i = 1; i <= 4; i++) {
    result *= i;
}

Question 4 of 5

Which loop correctly prints the values 10, 8, 6, 4, 2?

Question 5 of 5

What happens when this code runs?

int[] arr = {3, 7, 1};
for (int i = 0; i <= arr.length; i++) {
    System.out.println(arr[i]);
}