Skip to main content

Section 4.2 Iteration & For Loops

Iteration is a fundamental concept in programming—no matter which language you started with. In Java, loops let us repeat a block of code without resorting to copy-paste. In this section, we’ll begin with the for loop, a “definite loop” that neatly packages initialization, condition, body, and update all in one place. Even if you’ve used loops in other languages, you’ll see that Java’s approach is similar, with just a few syntactic details to remember.

Subsection 4.2.1 Anatomy of a For Loop

A Java for loop typically has four main parts. Let’s label them clearly:
  1. Initialization: Sets up a loop variable before the loop begins. For example, int i = 0.
  2. Condition: A Boolean expression checked before each iteration. If true, run the body; if false, exit the loop. For example, i < 10.
  3. Body: The statements that execute on each iteration. Even if there’s only one statement, it’s a good idea to use curly braces { } so you can easily expand the loop later.
  4. Update: Updates the loop variable at the end of each iteration (for instance, i++).
Putting these together, the basic syntax is:
for (initialization; condition; update) {
    // Loop body statements
}

Subsection 4.2.2 Example: Counting from 0 to 9

Here’s a simple example that prints the numbers from 0 through 9:
In this loop:
  • int i = 0 is the initialization.
  • i < 10 is the condition.
  • i++ is the update.
  • The body prints the current value of i each time.

Subsection 4.2.3 Common Loop Pitfalls

Even if your loop syntax is correct, certain pitfalls frequently trip up developers. Let’s look at three:
  • Off-by-One Errors: Make sure the loop condition exactly matches the count of iterations you want. For instance:
    // Off-by-One Example:
    for (int i = 0; i <= 10; i++) {
        System.out.println(i);
    }
    
    If you only intended to print ten numbers (0-9), using i <= 10 actually prints eleven (0..10). Here’s how the values go:
    i: 0 1 2 3 4 5 6 7 8 9 10  // 11 iterations total!
    
    To fix this, change i <= 10 to i < 10, so the loop stops at 9.
  • Infinite Loops: If the update step is missing or incorrect, the condition might never become false:
    // Infinite Loop Example:
    for (int i = 0; i < 10; ) {
        System.out.println(i);
        // Oops, missing i++ or some update
    }
    
    Because i never changes from 0, i < 10 is always true, so we loop forever.
  • Syntax Mistakes: A for loop’s header requires semicolons to separate the three parts, and braces { } around the body if there’s more than one statement. For example:
    // Syntax Mistake Example:
    // for (int i = 0 i < 10 i++)  // missing semicolons
    //     System.out.println(i)    // missing braces
    
    // Correct form:
    for (int i = 0; i < 10; i++) {
        System.out.println(i);
    }
    
    A small syntax error can prevent the code from compiling or lead to subtle bugs when you add more statements later.

Subsection 4.2.4 Exiting Early with break

While understanding proper loop construction helps avoid most issues, sometimes intentional early termination makes code clearer and more efficient. Sometimes you want to stop a loop before its condition naturally becomes false—perhaps when you’ve already found what you’re looking for or encountered an invalid value. In Java, you can exit a loop immediately with the break statement.
Let’s consider an example where we’re searching an array for a special key value. Once we find it, continuing the loop is unnecessary. Here’s how we might use break to exit early:
// Exiting a Loop with break
public class BreakDemo {
    public static void main(String[] args) {
        int[] numbers = { 3, 8, 12, 5, 7 };
        int key = 12;
        boolean foundKey = false;

        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == key) {
                System.out.println("Key found at index " + i);
                foundKey = true;
                break;  // Exit loop immediately
            }
        }

        if (!foundKey) {
            System.out.println("Key not found!");
        }
    }
}
In this snippet:
  • We loop over the array indices from 0 to numbers.length - 1.
  • Whenever numbers[i] matches key, we print a message and call break.
  • The for loop terminates immediately, skipping the rest of the iteration steps.
Why Use break?
  • Efficiency: If you’ve accomplished your goal—like finding a matching item—there’s no reason to keep iterating.
  • Clarity: Sometimes, exiting on specific conditions is clearer than writing a more complicated loop condition or control logic.
Note: Although break can simplify certain tasks, overusing it may complicate code flow—especially if multiple break statements appear scattered around. Typically, you want your loop condition to govern when you exit, but break is a handy tool for those exceptions when you must bail out early.

Subsection 4.2.5 Interactive Exercises: Practice with Loops

Now that you’ve seen standard loop patterns, common pitfalls, and the break statement, try these exercises. You may use break where appropriate, but remember to think about the loop’s overall logic and how break affects it.

Checkpoint 4.2.1.

Off-by-One Exercise. The code below intends to print exactly the first 10 integers, 0 through 9. However, it actually prints 11 values (0 through 10). Study the loop boundaries, and modify the loop so that it produces 10 lines of output, from 0 to 9 inclusive.
Hint: Check how many times the loop runs if the condition is i <= 10 vs i < 10. Remember to reason about the final integer at which the loop stops.

Checkpoint 4.2.2.

Infinite Loop Exercise. The code below never stops. Currently, the loop condition i < 5 remains true forever, because i is not updated inside the loop. Your goal: Insert an update step that ensures i eventually reaches 5, causing the loop to end.
Hint: Typically, you’d increment i, but you might also consider decrementing or adjusting the condition in a different manner. Use whichever approach you prefer, so long as the loop prints 0,1,2,3,4 and then stops.

Checkpoint 4.2.3.

Summation Exercise. Write a loop that calculates the sum of integers from 1 up to a certain n. Right now, the code is missing the loop logic. Your tasks:
  1. Prompt for n or set n to some integer in the code (e.g., 5 or 10).
  2. Use a for loop to accumulate the sum of all integers from 1..n.
  3. Print the final sum.
Example: If n is 5, output should be 15. If n is 10, output should be 55. Hint: Consider int sum = 0; before the loop. Carefully pick your starting and ending conditions to include all needed integers.

Subsection 4.2.6 Preview: Other Java Loops

Besides the for loop, Java also offers while and do-while. Both use a similar idea: run the body repeatedly while a condition holds true. The do-while loop ensures the body runs at least once before checking the condition. We’ll explore these in more detail next, but the principles are largely the same (watch for updates, watch your condition, and guard against infinite loops).

Subsection 4.2.7 Summary

We covered the for loop in Java, highlighting its four parts: initialization, condition, loop body, and update. You saw a simple example that prints numbers from 0 to 9, then explored common pitfalls—off-by-one errors, infinite loops, and syntax gotchas—and practiced them in code. Next, we’ll look at while and do-while, and eventually move on to arrays (so we can loop over large sets of data) and even a custom “iterable” class.
You have attempted of activities on this page.