for Loops
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:
- Start with bag #1.
- As long as you haven't finished all 50 bags...
- ...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.
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];
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.
- 1Initialization
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. - 2Boolean Expression (Condition)
i < 10;This is the gatekeeper. Before each loop cycle begins, Java checks this condition. If it'strue, the loop body runs. If it'sfalse, 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. - 3Update
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:
- 1Initialize
int iis created and set to0. This only happens once. - 2CheckIs
i < 5? Yes,0 < 5is true. - 3Execute BodyThe code inside the
{}runs.System.out.println(0);prints "0". - 4Update
i++runs.iis now1. - 5CheckIs
i < 5? Yes,1 < 5is true. - 6Execute Body
System.out.println(1);prints "1". - 7Update
i++runs.iis now2. ...and so on. This continues until:
- CheckIs
i < 5? Let's sayiis now4. Yes,4 < 5is true. - Execute Body
System.out.println(4);prints "4". - Update
i++runs.iis now5. - CheckIs
i < 5? No,5 < 5is false. - StopThe 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
forloop's initialization becomes a statement right before thewhileloop. - The
forloop's boolean expression becomes thewhileloop's condition. - The
forloop's update becomes the very last line inside thewhileloop'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.
See it in action
Worked examples
Let's walk through a couple of common scenarios you'll see on the AP exam.
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:
- 1Identify the RepetitionThe 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 aforloop that counts from 1 ton. - 2Set 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; } - 3Construct the Loop
- InitializationWe need a counter that starts at 1. So,
int i = 1;. - ConditionWe 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". - UpdateAfter each number, we move to the next one. So,
i++.
- Initialization
- 4Combine and Add LogicInside the loop, we just need to add the current value of our counter (
i) to oursum.
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!
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:
- 1Identify the RepetitionWe need to access each character of the string. A
forloop is perfect. But this time, we need to count down, not up. - 2Construct the Loop
- InitializationWhere should we start? We want the last character. The index of the last character in a string
siss.length() - 1. So,int i = s.length() - 1;. - ConditionWhen should we stop? We want to include the character at index 0. So, we should keep going as long as
iis greater than or equal to 0. The condition isi >= 0;. - UpdateWe're counting down, so our update is
i--.
- Initialization
- 3Combine and Add LogicInside the loop, we can get the character at the current index
iusings.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.
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 1You can start your loop at 2. What would your update statement need to be to only hit the even numbers?
- Hint 2Alternatively, you could loop from 1 to 20 and use an
ifstatement 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.
Practice — 8 questions
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.
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
- 2.8.A: Develop code to represent iterative processes using for loops and determine the result of these processes.
- 2.8.A.1
- A for loop is a type of iterative statement. There are three parts in a for loop header: the initialization, the Boolean expression, and the update.
- 2.8.A.2
- In a for loop, the initialization statement is only executed once before the first Boolean expression evaluation. The variable being initialized is referred to as a loop control variable. The Boolean expression is evaluated immediately after the loop control variable is initialized and then following each execution of the increment statement until it is false. In each iteration, the update is executed after the entire loop body is executed and before the Boolean expression is evaluated again.
- 2.8.A.3
- A for loop can be rewritten into an equivalent while loop (and vice versa).
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];
Read what Saavi narrates
Hi everyone, it's Saavi from Shrutam. Let's talk about one of the most important tools in your programming toolkit.
Imagine you're helping a friend with a bake sale. You have to pack fifty goodie bags, and each one needs exactly three cookies. You could count them out one by one... but that's slow and you're bound to make a mistake.
What you really want is a system. A predictable process you can repeat. Start with bag number one... as long as you haven't finished all fifty bags... put three cookies in, and move to the next one.
That's exactly what a `for` loop does in our code. It's a clean, organized way to run a block of code over and over, especially when you know exactly how many times you need to repeat it.
Let's look at a classic example: adding up all the numbers from one to a hundred.
First, we need a variable to hold our total, let's call it 'sum', and we'll start it at zero.
Then we build our `for` loop. The header has three parts. First, the initialization. We create a counter variable, let's call it 'i', and set it to one. This only happens once.
Second, the condition. We want to keep going as long as 'i' is less than or equal to one hundred. The loop checks this condition before every single run.
Third, the update. After we add a number to our sum, we need to move to the next one. So, we'll use 'i plus plus' to increment our counter. This happens at the end of each cycle.
Inside the loop, the only thing we do is add the current value of 'i' to our 'sum' variable.
The loop runs... for one, two, three... all the way to one hundred. When 'i' becomes one hundred and one, the condition is no longer true, the loop stops, and the code returns our final sum.
Now, a really common mistake here is called an "off-by-one" error. If your condition was 'i is less than 100' instead of 'less than or equal to', your loop would stop at ninety-nine. You'd miss the last number! So always, always double-check your loop's boundaries.
`for` loops might feel a little strange at first, but once you get the rhythm of 'initialize, check, update', you'll find yourself using them everywhere. Keep practicing, and you'll get it. You've got this.
Using `<` when you mean `<=` (or vice versa) makes your loop run one too many or one too few times. This is a very common bug.
Before finalizing your loop, mentally trace the first and last iterations. For a loop `for (int i = 0; i < 5; i++)`, think: "It starts at 0. The last run is when `i` is 4. It runs for 0, 1, 2, 3, 4. That's 5 times."
The semicolon acts as an empty statement. This code creates a loop that does nothing 10 times. The block `{...}` that follows is treated as a separate, unrelated piece of code that runs only once *after* the loop is finished.
Never put a semicolon directly after the `)` of a `for` loop header.
// CORRECT
for (int i = 0; i < 10; i++) {
System.out.println("This runs 10 times.");
}
For a string of length 4, the valid indices are 0, 1, 2, 3. The code above tries to access `s.charAt(4)`, which doesn't exist, causing a `StringIndexOutOfBoundsException`.
Always loop from `0` to `< length` for forward loops, or from `length - 1` down to `>= 0` for reverse loops.
// WRONG - will crash
String s = "test";
for (int i = 1; i <= s.length(); i++) {
System.out.println(s.charAt(i));
}
While technically allowed, this makes the loop's behavior extremely difficult to predict. The `for` loop's update expression (`i++`) will *still* run, leading to unexpected jumps.
Let the `for` loop's update section be the *only* place the loop control variable is changed. If you need more complex control flow, a `while` loop might be a better choice.
// CONFUSING AND DANGEROUS
for (int i = 0; i < 10; i++) {
System.out.println(i);
if (i == 3) {
i = 7; // Don't do this!
}
}