SECTION 1
Historical Context & Motivation
Imagine you need to print the numbers 1 through 1,000 on the screen. Without loops, you would need to write one thousand separate print statements — tedious, error-prone, and almost impossible to maintain. Early programmers faced exactly this problem. The idea of counter-controlled repetition — running a block of code a specific number of times by tracking a counter — became one of the most fundamental ideas in all of programming.
1957 • FORTRAN Introduces DO Loops
1972 • C Language Defines the Modern for Loop
1995 • Java Adopts the C-Style for Loop
2004 • Java 5 Adds the Enhanced for Loop
The central question this lesson addresses is straightforward but powerful: how do you tell a computer to repeat an action a known number of times, while keeping track of which repetition it is on? The Java for loop provides an elegant, compact answer.
SECTION 2
Core Principles & Definitions
A for loop is a control-flow statement that lets you repeat a block of code a predetermined number of times. It bundles three critical pieces — initialization, condition, and update — into a single header line, making it the cleanest tool for counter-controlled repetition. Before diving into syntax, you should understand the foundational ideas behind every for loop.
Initialization
i) to its starting value. This happens exactly once, before the first iteration.Condition (Boolean Test)
Loop Body
Update (Increment/Decrement)
Termination
KEY TAKEAWAY
for (int rep = 1; rep <= 20; rep++).SECTION 3
Visual Explanation — Anatomy of a For Loop
for (int i = 0; i < 5; i++). The initialization (violet) runs once. The condition diamond (cyan) is checked before every iteration. If true, the body (pink) executes, followed by the update (amber), which loops back to the condition. When the condition is false (red path), execution exits the loop entirely.Study the flowchart carefully. Notice that the initialization is not inside the cycle — it happens only once, before the loop starts. The cycle itself is a three-step dance: check the condition, run the body, and execute the update. This cycle repeats until the condition becomes false. If the condition is false the very first time, the body never runs at all — the loop simply has zero iterations.
SECTION 4
How the For Loop Works — Syntax & Execution
The General Syntax
FOR LOOP SYNTAX
initialization — declares and sets the counter variable (e.g., int i = 0). condition — a boolean expression evaluated before each iteration (e.g., i < 10). update — modifies the counter after each iteration (e.g., i++).
All three components sit inside the parentheses after the keyword for, separated by semicolons. The curly braces { } wrap the body — the statements that repeat. Let's trace through a concrete example.
Counting Iterations
NUMBER OF ITERATIONS
For a loop for (int i = start; i < end; i += step), the total number of times the body runs equals (end − start) ÷ step, using integer division. For the common case where step is 1, the loop simply runs end − start times.
Execution Order — Step by Step
- Step 1: The initialization expression runs exactly once.
- Step 2: The condition is evaluated. If false, skip to Step 5.
- Step 3: The loop body executes all of its statements.
- Step 4: The update expression runs, then control returns to Step 2.
- Step 5: The loop terminates. Execution continues with the statement after the closing brace.
Common Pitfall: Off-by-One Errors
i <= 5 versus i < 5 changes whether the loop runs 5 or 6 times (when starting from 0). Always double-check your boundary values. An off-by-one error is one of the most frequent bugs in programming.SECTION 5
For Loop Variations & Trace Table
The standard for loop is flexible enough to count up, count down, skip values, or iterate by any step size. Below is a trace table showing how the counter variable i changes on each pass through the loop for (int i = 0; i < 5; i++). A trace table is a powerful debugging tool that records the state of every variable at each iteration.
| Iteration | i before condition | Condition (i < 5) | Body runs? | i after update |
|---|---|---|---|---|
| 1 | 0 | true | Yes — prints 0 | 1 |
| 2 | 1 | true | Yes — prints 1 | 2 |
| 3 | 2 | true | Yes — prints 2 | 3 |
| 4 | 3 | true | Yes — prints 3 | 4 |
| 5 | 4 | true | Yes — prints 4 | 5 |
| — | 5 | false | No — loop exits | — |
Trace table for for (int i = 0; i < 5; i++)
The key insight is that the three parts of the for-loop header are fully customizable. You can start at any integer, use any comparison operator (<, <=, >, >=, !=), and update the counter using addition, subtraction, multiplication, or any other arithmetic operation. This flexibility is what makes the for loop so powerful for counter-controlled repetition.
SECTION 6
Worked Example — Summing Integers 1 to N
Let's solve a classic problem: write a Java program that calculates the sum of all integers from 1 to 100. We will use a for loop with a counter variable to accumulate the total.
Calculate the Sum of 1 + 2 + 3 + … + 100
- 1
Step 1 — Identify the Loop Bounds
We want to add every integer from 1 through 100. The counterishould start at 1 and end at 100 (inclusive). Usingi <= 100as the condition ensures 100 is included.Start = 1, End = 100, Step = 1 - 2
Step 2 — Declare an Accumulator Variable
Before the loop, we declareint sum = 0;to hold the running total. This variable is called an accumulator because it accumulates (builds up) a result across iterations.int sum = 0; - 3
Step 3 — Write the For Loop
We construct the loop:for (int i = 1; i <= 100; i++). Inside the body, we add the current value ofitosumusing the statementsum += i;which is shorthand forsum = sum + i;.for (int i = 1; i <= 100; i++) { sum += i; } - 4
Step 4 — Trace a Few Iterations
After iteration 1: sum = 0 + 1 = 1. After iteration 2: sum = 1 + 2 = 3. After iteration 3: sum = 3 + 3 = 6. The pattern continues, adding the next integer each time. - 5
Step 5 — Print the Result
After the loop completes (whenireaches 101 and the conditioni <= 100becomes false), we print the result withSystem.out.println(sum);. The output is 5050 — matching the famous formula n × (n + 1) / 2 = 100 × 101 / 2.Output: 5050
Full Program Listing
public class SumExample {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("Sum = " + sum);
}
}SECTION 7
For Loop vs. While Loop — When to Use Each
Java provides multiple loop structures, but the two most common are the for loop and the while loop. Although they can technically accomplish the same tasks, each has situations where it is the better choice. Understanding when to reach for each tool is an important programming skill.
| Feature | for loop | while loop |
|---|---|---|
| Best for | Counter-controlled repetition — when you know in advance how many iterations you need | Sentinel-controlled repetition — when the number of iterations depends on runtime input or conditions |
| Counter management | Initialization, condition, and update are all in the header — easy to read at a glance | Counter must be declared before the loop and updated inside the body — spread across multiple lines |
| Risk of infinite loop | Lower — the update is built into the header, so it is harder to forget | Higher — if you forget to update the counter in the body, the condition never becomes false |
| Scope of counter | Counter variable is scoped to the loop and cannot be used after it ends | Counter variable remains accessible after the loop completes |
| Readability | Very compact — all loop logic is on one line | More verbose — loop logic is distributed across the method |
Comparing for and while loops in Java
KEY TAKEAWAY
SECTION 8
Connection to Advanced Concepts
The for loop you have learned is a stepping stone to more advanced programming patterns. As you grow as a programmer, you will encounter nested loops, the enhanced for-each loop, and eventually more abstract iteration tools. Understanding the basic counter-controlled for loop is the foundation for all of these.
| Basic For Loop Concept | Advanced Extension | Why It Matters |
|---|---|---|
| Single for loop iterating over indices | Nested for loops — a loop inside a loop | Required for processing 2D arrays (grids), generating multiplication tables, and many sorting algorithms |
| Counter-based array traversal | Enhanced for-each loop — for (int x : arr) | Simplifies code when you need every element but do not need the index |
| Fixed iteration count | Iterators and Streams (Java 8+) | Functional-style processing of collections; builds on the same idea of visiting each element in sequence |
| Loop with accumulator | Recursion | An alternative to loops where a method calls itself; many recursive problems can also be solved with for loops |
From basic for loops to advanced iteration patterns
As you move into AP Computer Science A and beyond, you will discover that the for loop is used in nearly every data structure and algorithm. Searching through an array, sorting values, and building strings character by character all rely on the counter-controlled repetition pattern you are learning now. Master this concept thoroughly, and you will have a head start on every topic that comes next.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
for (int i = 0; i < 10; i++), explain the purpose of each of the three parts separated by semicolons. How many times does the loop body execute, and what is the value of i when the loop terminates?Show answer
int i = 0, is the initialization — it creates the counter variable and sets it to 0, running only once. The second part, i < 10, is the condition — it is checked before each iteration, and the body only runs when it is true. The third part, i++, is the update — it increments i by 1 after each iteration. The body executes 10 times (for i values 0 through 9). When the loop terminates, i equals 10 because i++ set it to 10, making the condition 10 < 10 false.Question 2: BASIC CALCULATION
for (int i = 2; i <= 10; i += 2) { System.out.print(i + " "); }Show answer
2 4 6 8 10. The loop starts at i = 2 and increments by 2 each time (i += 2). It runs as long as i ≤ 10. The values of i on each iteration are 2, 4, 6, 8, and 10 — giving five iterations total. After i reaches 10 and the update makes it 12, the condition 12 ≤ 10 is false and the loop stops.Question 3: INTERMEDIATE
Show answer
for (int i = 20; i >= 1; i--) { System.out.println(i); }. This counts down because the initialization is 20, the condition requires i ≥ 1, and the update is i-- (decrement by 1). To print only even numbers, change the update to decrement by 2: for (int i = 20; i >= 2; i -= 2) { System.out.println(i); }. Starting at 20 and subtracting 2 each time produces 20, 18, 16, …, 4, 2. Alternatively, you could keep i-- and add an if statement checking i % 2 == 0, but using i -= 2 is more efficient.Question 4: APPLIED
int[] scores = {85, 92, 78, 95, 88};. Write a for loop that computes and prints the average. Explain each part of your loop.Show answer
int[] scores = {85, 92, 78, 95, 88}; int sum = 0; for (int i = 0; i < scores.length; i++) { sum += scores[i]; } double average = (double) sum / scores.length; System.out.println(average); The initialization int i = 0 starts at the first index. The condition i < scores.length ensures we do not go past the last element (index 4). The update i++ moves to the next index. The accumulator sum collects all five scores (sum = 438), and dividing by 5 gives an average of 87.6. The cast to double ensures decimal precision.Question 5: CRITICAL THINKING
for (int i = 1; i != 10; i += 3) { System.out.println(i); } Will this loop ever terminate? Explain your reasoning. What values will be printed? What would happen if the condition were changed to i < 10 instead?Show answer
i != 10 — wait, actually i does hit exactly 10 (1 → 4 → 7 → 10), so the condition becomes false when i equals 10 and the loop terminates. The printed values are 1, 4, 7. However, if the step were 2 instead of 3 (1, 3, 5, 7, 9, 11, …), i would skip over 10 entirely and the loop would run forever. Using i < 10 is safer because it catches any value that exceeds 10, regardless of step size. This illustrates why relational operators (<, <=) are preferred over != in for-loop conditions — they are more robust against off-by-one and step-size mismatches.SUMMARY
Lesson Summary
Summary
The Java for loop is the go-to tool for counter-controlled repetition — repeating a block of code a specific number of times. Its three-part header packs the initialization (setting the counter), the condition (testing whether to continue), and the update (modifying the counter) into a single, readable line separated by semicolons.
The loop executes in a predictable cycle: initialize once, then repeatedly check the condition → run the body → update the counter. The loop terminates when the condition becomes false. You can count up, count down, skip values, or use multiplication steps by customizing these three components. Watch out for off-by-one errors by carefully choosing between < and <=. Choose a for loop over a while loop when you know the iteration count in advance, and use trace tables to verify your loop logic before running the program.