Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

for Loops

Lesson ~10 min read 8 MCQs

In simple terms: In simple terms, a `for` loop is a clean way to write code that repeats a specific number of times, like counting from 1 to 10 or processing every item in a list.

Why this matters

Imagine you're helping your friend Priya run a booth at the school's fall festival. You're in charge of making 50 goodie bags, and each one needs exactly three pieces of candy. You could manually count them out: "one, two, three... okay, next bag. One, two, three..." but you'd lose track fast.

What you really want is a system. A predictable, repeatable process:

  1. Start with bag #1.
  2. As long as you haven't finished all 50 bags...
  3. ...put three candies in the current bag, then move to the next one.

This is the exact kind of thinking a for loop helps us automate in our code. It's a powerful tool for any task that involves counting or repeating a set number of times. Today, we'll break down how to build and use them, so you can stop counting manually and let your program do the work.

Priya's Goodie Bag Assembly Line

Concept overview

flowchart TD
    A[Start] --> B{for (init; condition; update)};
    B -- 1. Run init (once) --> C{Is condition true?};
    C -- Yes --> D[Execute loop body];
    D --> E[Run update statement];
    E --> C;
    C -- No --> F[End Loop];
    F --> G[Continue program];
This is a flowchart diagram illustrating the execution path of a for loop. It starts with an initialization step that runs once, then enters a cycle: first, a condition is checked. If true, the loop body and an update statement are executed, and the flow returns to the condition check. If the condition is false, the loop ends.

Core explanation

In the last lesson, you met the while loop, which is great for repeating code as long as some condition is true. Now, let's meet its more structured cousin: the for loop. A for loop is perfect for count-controlled iteration, where you know you need to do something exactly 5, 10, or 100 times.

The Anatomy of a for Loop

The power of a for loop is that it bundles all the logic for counting into one clean line. The header of a for loop has three distinct parts, separated by semicolons.

for (initialization; boolean expression; update)

Let's use an analogy of a road trip from Boston to Chicago.

  1. 1
    Initialization
    int i = 0; This is where you set up your counter, or loop control variable. It runs only once at the very beginning. Think of this as setting your car's trip odometer to 0 before you pull out of the driveway.
  2. 2
    Boolean Expression (Condition)
    i < 10; This is the gatekeeper. Before each loop cycle begins, Java checks this condition. If it's true, the loop body runs. If it's false, the loop stops completely, and the program moves on. This is like asking, "Have we driven 10 miles yet?" before you start the next leg of your journey.
  3. 3
    Update
    i++ This part runs after the code inside the loop body has finished, but before the condition is checked again for the next cycle. This is you driving one more mile. After you've done your "driving" (the loop body), your odometer clicks up.

Here’s a simple example that prints the numbers 0 through 4:

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

Let's trace the execution step-by-step:

  1. 1
    Initialize
    int i is created and set to 0. This only happens once.
  2. 2
    Check
    Is i < 5? Yes, 0 < 5 is true.
  3. 3
    Execute Body
    The code inside the {} runs. System.out.println(0); prints "0".
  4. 4
    Update
    i++ runs. i is now 1.
  5. 5
    Check
    Is i < 5? Yes, 1 < 5 is true.
  6. 6
    Execute Body
    System.out.println(1); prints "1".
  7. 7
    Update
    i++ runs. i is now 2. ...and so on. This continues until:
  • Check
    Is i < 5? Let's say i is now 4. Yes, 4 < 5 is true.
  • Execute Body
    System.out.println(4); prints "4".
  • Update
    i++ runs. i is now 5.
  • Check
    Is i < 5? No, 5 < 5 is false.
  • Stop
    The loop terminates. The program continues with whatever code comes after the loop's closing brace }.

for Loops vs. while Loops

The AP Exam expects you to know that any for loop can be rewritten as a while loop, and vice versa. This is a great way to truly understand the three parts of the for loop header.

Let's convert our for loop into a while loop.

The for loop:

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

The equivalent while loop:

// 1. Initialization happens BEFORE the loop
int i = 0;

// 2. The boolean expression is the while condition
while (i < 5) {
  // The loop body is the same
  System.out.println(i);

  // 3. The update is the LAST thing in the loop body
  i++;
}

See how the three parts just get rearranged?

  • The for loop's initialization becomes a statement right before the while loop.
  • The for loop's boolean expression becomes the while loop's condition.
  • The for loop's update becomes the very last line inside the while loop's body.

This equivalence shows why for loops are so useful. They don't add new functionality, but they organize the code for count-based loops much more cleanly, reducing the chance you'll forget to initialize or update your counter variable. You're much less likely to accidentally write an infinite loop with a for loop than with a while loop.

The For Loop's Flow of Control
Tracing a simple `for` loop: `for (int i = 0; i < 5; i++)`

See it in action

Java Code

      
      
Condition Check
Variables
Console Output

      
Step 0 / 0

Worked examples

Let's walk through a couple of common scenarios you'll see on the AP exam.

Example 1

Summing a Range of Numbers

Problem: Write a method that calculates the sum of all integers from 1 up to and including a given number n. For example, if n is 4, the method should return 1 + 2 + 3 + 4 = 10.

Solution Walkthrough:

  1. 1
    Identify the Repetition
    The core task is "adding a number." We need to repeat this task for every number from 1 to n. This sounds like a job for a for loop that counts from 1 to n.
  2. 2
    Set up the "Total"
    Before we start adding, our sum is zero. We need a variable to hold our running total. Let's call it sum.
    public int sumUpTo(int n) {
      int sum = 0; // Start with a sum of 0
      // Loop will go here
      return sum;
    }
  3. 3
    Construct the Loop
    • Initialization
      We need a counter that starts at 1. So, int i = 1;.
    • Condition
      We want to keep looping as long as our counter is less than or equal to n. So, i <= n;. Using <= is crucial here because the problem says "up to and including n".
    • Update
      After each number, we move to the next one. So, i++.
  4. 4
    Combine and Add Logic
    Inside the loop, we just need to add the current value of our counter (i) to our sum.

Final Code:

public int sumUpTo(int n) {
  int sum = 0; // Initialize our total

  // Loop from 1 up to n (inclusive)
  for (int i = 1; i <= n; i++) {
    // Add the current number to the sum
    sum = sum + i; // or more concisely: sum += i;
  }

  return sum; // Return the final calculated sum
}

Where students go wrong: The most common mistake here is an "off-by-one" error in the loop condition. If you write i < n, your loop will stop one number too early. For n = 4, it would only sum 1+2+3, giving 6 instead of 10. Always double-check your boundary conditions!

Example 2

Processing a String in Reverse

Problem: Write code to print the characters of a string, one per line, but in reverse order. For the string "hello", it should print: o l l e h

Solution Walkthrough:

  1. 1
    Identify the Repetition
    We need to access each character of the string. A for loop is perfect. But this time, we need to count down, not up.
  2. 2
    Construct the Loop
    • Initialization
      Where should we start? We want the last character. The index of the last character in a string s is s.length() - 1. So, int i = s.length() - 1;.
    • Condition
      When should we stop? We want to include the character at index 0. So, we should keep going as long as i is greater than or equal to 0. The condition is i >= 0;.
    • Update
      We're counting down, so our update is i--.
  3. 3
    Combine and Add Logic
    Inside the loop, we can get the character at the current index i using s.charAt(i) and print it.

Final Code:

String message = "hello";

// Initialize at the last index, count down to 0
for (int i = message.length() - 1; i >= 0; i--) {
  System.out.println(message.charAt(i));
}

Where students go wrong: Many students instinctively start the loop at message.length(). This will cause an StringIndexOutOfBoundsException because the valid indices are from 0 to length() - 1. Remember that indexing almost always starts at 0 in Java.

Tracing `sumUpTo(4)`
Avoiding Off-by-One Errors in Loop Conditions
Processing a String in Reverse

Try it yourself

Ready to try a few on your own? Don't worry about getting it perfect on the first try. The goal is to start thinking in loops.

Problem 1: The Even Number Printer Write a for loop that prints all the even numbers between 1 and 20 (inclusive). The output should be 2, 4, 6, ... 20.

  • Hint 1
    You can start your loop at 2. What would your update statement need to be to only hit the even numbers?
  • Hint 2
    Alternatively, you could loop from 1 to 20 and use an if statement inside the loop with the modulus operator (%) to check if a number is even before printing it. Both approaches are valid!

Problem 2: The Countdown Your school basketball team, the Wildcats, is playing their rival. Write a for loop that simulates a countdown for the final seconds of the game. It should print: 10... 9... ... 1... WILDCATS WIN!

  • Hint: You'll want to count down, not up. What should your initialization, condition, and update be? The final print statement should happen after the loop is finished.
Countdown Loop Example