Introduction to for Loops

In the previous chapter, we looked at while loops, which repeat code as long as a condition is true. But what if you know exactly how many times you want to repeat something? That is where the for loop shines! for loops are the go-to tool for programmers when they need to count, traverse through a sequence, or repeat an action a specific number of times. Don't worry if it looks a bit crowded at first—once you understand the three "ingredients" in the header, you'll see it’s just a very organized way of writing a loop.

The Anatomy of a for Loop

A for loop packs three important instructions into one single line called the header. This keeps your code clean and helps prevent errors like forgetting to update your counter variable.

The standard structure looks like this:

for (initialization; boolean expression; iteration statement)
{
    // Body: This code runs every time the condition is true
}

1. Initialization

This happens only once, at the very beginning. You usually create a "counter" variable here, such as \( i = 0 \). It sets the starting point for your loop.

2. Boolean Expression (The Condition)

Before every "lap" of the loop, Java checks this condition. If it is true, the loop runs. If it is false, the loop ends immediately. For example, \( i < 10 \) tells the loop to keep going as long as \( i \) is less than 10.

3. Iteration Statement (The Update)

This happens after the code inside the loop finishes. It changes the counter variable (like \( i++ \)) so that the loop eventually reaches the end. Without this, you might be stuck in an infinite loop!

Key Takeaway: The for loop header is a "all-in-one" shop for starting, checking, and updating your loop counter.

The Flow of Execution: Step-by-Step

One of the most common mistakes is getting the order of execution wrong. Let’s trace a loop that prints numbers from 1 to 3:

for (int \( i = 1 \); \( i <= 3 \); \( i++ \)) {
    System.out.println(\( i \));
}

  1. Start: Create \( i \) and set it to \( 1 \).
  2. Check: Is \( i <= 3 \)? Yes (\( 1 <= 3 \)).
  3. Body: Print \( 1 \).
  4. Update: Increase \( i \) to \( 2 \) (using the \( i++ \) operator).
  5. Check: Is \( 2 <= 3 \)? Yes.
  6. Body: Print \( 2 \).
  7. Update: Increase \( i \) to \( 3 \).
  8. Check: Is \( 3 <= 3 \)? Yes.
  9. Body: Print \( 3 \).
  10. Update: Increase \( i \) to \( 4 \).
  11. Check: Is \( 4 <= 3 \)? No! The loop stops.

Note: The initialization step ONLY happens once. The update happens AFTER the body code executes.

Common Patterns in for Loops

You can adjust the header to count in different ways depending on your goal.

Counting Up

To count from 0 to 4:
for (int \( i = 0 \); \( i < 5 \); \( i++ \))

Counting Down

To count down from 10 to 1:
for (int \( i = 10 \); \( i > 0 \); \( i-- \))

Counting by Steps

You aren't limited to adding 1. You can use compound assignment operators like \( += \).
To count even numbers from 0 to 10:
for (int \( i = 0 \); \( i <= 10 \); \( i += 2 \))

Did you know? In computer science, we almost always start counting at \( 0 \) instead of \( 1 \). This is a standard convention you'll see again when we study Strings and Arrays!

Common Mistakes to Avoid

  • Off-by-One Errors: This happens when your loop runs one time too many or one time too few. Always double-check if you should use \( < \) or \( <= \). For example, \( i = 0; i < 5 \) runs 5 times, but \( i = 0; i <= 5 \) runs 6 times.
  • Infinite Loops: If your condition never becomes false (e.g., you are counting up but your condition checks if \( i \) is greater than a negative number), your program will hang.
  • Semicolon Errors: Never put a semicolon directly after the for loop header.
    Incorrect: for (...); { ... }
    This makes Java think the loop body is empty!

Analogy: The Track Coach

Think of a for loop as a track coach standing with a clipboard:

  • Initialization: The coach tells the runner, "Start at Lap 1."
  • Boolean Expression: The coach checks, "Have you finished 10 laps yet?"
  • Body: The runner runs one lap.
  • Iteration Statement: As the runner passes the coach, the coach clicks the counter: "That’s one more lap completed."

Quick Review

Variable Scope: If you declare the variable \( i \) inside the for loop header, that variable only exists inside that loop. Once the loop finishes, \( i \) is destroyed!

Informal Run-Time: In Unit 2.12, you will learn to compare algorithms. For now, remember that a for loop running \( n \) times means the statements inside the body will be executed \( n \) times. If you change the loop to run \( 2n \) times, the execution count doubles.

Key Takeaway Summary: Use for loops when the number of iterations is known or can be calculated before the loop starts. The header consists of initialization, condition, and update, separated by semicolons.

Note: For more complex logic, such as loops inside other loops, check out the chapter on "Nested Iteration." For loops that handle text, see "Implementing String Algorithms."