JAVA • CONTROL FLOW

For Loops — Use for loops for counter-controlled repetition

Master the for loop to repeat code a precise number of times with a built-in counter variable.

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
IBM's FORTRAN language introduced the DO loop, the first widely-used counter-controlled loop. Programmers could specify a start value, end value, and step size to repeat calculations automatically.
1972
C Language Defines the Modern for Loop
Dennis Ritchie's C language introduced the three-part for loop syntax — initialization, condition, and update — all on a single line. This elegant design became the template for dozens of languages that followed.
1995
Java Adopts the C-Style for Loop
When James Gosling and his team at Sun Microsystems released Java, they kept the familiar C-style for loop syntax. Java's for loop remains one of the most commonly used control-flow structures in the language today.
2004
Java 5 Adds the Enhanced for Loop
Java 5 introduced the enhanced for-each loop for iterating over collections and arrays. However, the traditional counter-controlled for loop remains essential whenever you need an index or a specific iteration count.

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.

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.

1

Initialization

The loop begins by creating and setting a counter variable (often called i) to its starting value. This happens exactly once, before the first iteration.
2

Condition (Boolean Test)

Before each iteration, Java evaluates a boolean condition. If the condition is true, the loop body executes. If it is false, the loop ends immediately.
3

Loop Body

The body contains the statements that run on each pass through the loop. This is where you place the code you want to repeat — printing, calculating, or updating data.
4

Update (Increment/Decrement)

After the body executes, the update expression modifies the counter variable (usually by adding 1). Then the condition is checked again, and the cycle continues.
5

Termination

Eventually the update pushes the counter past the condition's boundary, causing the condition to evaluate to false. The loop terminates and execution moves to the next statement after the loop.
✦ KEY TAKEAWAY
Think of a for loop like a gym coach counting push-ups. The coach starts at 1 (initialization), checks whether you have reached your target of 20 (condition), watches you do one push-up (body), then adds 1 to the count (update). When the count hits 21, the condition fails and the exercise is over. The for loop header is simply the coach's plan written on one line: for (int rep = 1; rep <= 20; rep++).

Visual Explanation — Anatomy of a For Loop

This flowchart traces the execution path of 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.

How the For Loop Works — Syntax & Execution

The General Syntax

FOR LOOP SYNTAX
for (initialization; condition; update) { body }
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
iterations = (end − start) / step
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

  1. Step 1: The initialization expression runs exactly once.
  2. Step 2: The condition is evaluated. If false, skip to Step 5.
  3. Step 3: The loop body executes all of its statements.
  4. Step 4: The update expression runs, then control returns to Step 2.
  5. Step 5: The loop terminates. Execution continues with the statement after the closing brace.
⚠️ Common Pitfall: Off-by-One Errors
Using 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.

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.

Trace table for for (int i = 0; i < 5; i++)
Iterationi before conditionCondition (i < 5)Body runs?i after update
10trueYes — prints 01
21trueYes — prints 12
32trueYes — prints 23
43trueYes — prints 34
54trueYes — prints 45
—5falseNo — loop exits—
Five common for-loop patterns: counting up from 0, counting down, stepping by 2, starting from a non-zero value, and using multiplication to double the counter on each pass. Each variation changes the initialization, condition, or update expression while keeping the same three-part structure.

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.

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 BoundsWe want to add every integer from 1 through 100. The counter i should start at 1 and end at 100 (inclusive). Using i <= 100 as the condition ensures 100 is included.
Start = 1, End = 100, Step = 1
2
Step 2 — Declare an Accumulator VariableBefore the loop, we declare int 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 LoopWe construct the loop: for (int i = 1; i <= 100; i++). Inside the body, we add the current value of i to sum using the statement sum += i; which is shorthand for sum = sum + i;.
for (int i = 1; i <= 100; i++) { sum += i; }
4
Step 4 — Trace a Few IterationsAfter 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 ResultAfter the loop completes (when i reaches 101 and the condition i <= 100 becomes false), we print the result with System.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); } }

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.

Comparing for and while loops in Java
Featurefor loopwhile loop
Best forCounter-controlled repetition — when you know in advance how many iterations you needSentinel-controlled repetition — when the number of iterations depends on runtime input or conditions
Counter managementInitialization, condition, and update are all in the header — easy to read at a glanceCounter must be declared before the loop and updated inside the body — spread across multiple lines
Risk of infinite loopLower — the update is built into the header, so it is harder to forgetHigher — if you forget to update the counter in the body, the condition never becomes false
Scope of counterCounter variable is scoped to the loop and cannot be used after it endsCounter variable remains accessible after the loop completes
ReadabilityVery compact — all loop logic is on one lineMore verbose — loop logic is distributed across the method
✦ KEY TAKEAWAY
Use a for loop when you can answer the question "how many times?" before the loop starts. Use a while loop when the stopping point depends on something that changes unpredictably, like user input or a sensor reading. Think of it like driving: a for loop is a planned road trip where you know the exact distance, while a while loop is like driving until you see a gas station.

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.

From basic for loops to advanced iteration patterns
Basic For Loop ConceptAdvanced ExtensionWhy It Matters
Single for loop iterating over indicesNested for loops — a loop inside a loopRequired for processing 2D arrays (grids), generating multiplication tables, and many sorting algorithms
Counter-based array traversalEnhanced for-each loop — for (int x : arr)Simplifies code when you need every element but do not need the index
Fixed iteration countIterators and Streams (Java 8+)Functional-style processing of collections; builds on the same idea of visiting each element in sequence
Loop with accumulatorRecursionAn alternative to loops where a method calls itself; many recursive problems can also be solved with for loops

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.

Practice Problems

PROBLEM 1 — CONCEPTUAL
In the for loop 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?
PROBLEM 2 — BASIC CALCULATION
What is the output of the following code? for (int i = 2; i <= 10; i += 2) { System.out.print(i + " "); }
PROBLEM 3 — INTERMEDIATE
Write a for loop that prints the numbers from 20 down to 1 (in descending order), each on its own line. Then modify the loop so it only prints even numbers in that range.
PROBLEM 4 — APPLIED
A teacher wants a program that calculates the average of test scores stored in an array int[] scores = {85, 92, 78, 95, 88};. Write a for loop that computes and prints the average. Explain each part of your loop.
PROBLEM 5 — CRITICAL THINKING
Consider the following loop: 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?

Lesson 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.

Varsity Tutors • Java • For Loops — Use for loops for counter-controlled repetition