Skip to content
Ameen Abozaid
PublishedBEG-013-L02

The for loop

  • Lesson 2 of 7
  • 10 min read
  • Beginner
On This Lesson 11 topics

Lesson Overview

In the last lesson you met the three parts of a loop and read a first for loop. This lesson makes you fluent: you will write counting loops that go up, go down, and step by more than one, and you will learn to trace a loop by hand, which is the fastest way to find a bug.

The track picture continues. The for loop is the track with a lap counter printed on the starting line: the start, the finish check, and the counter update are all written together in one place, in the parentheses. That makes for the natural choice when you know how many laps to run.

Why this matters: in the backend, "do something N times" and "do something for each number in a range" are everyday needs, and a clear for loop is the way to say it.

This lesson builds on BEG-013-L01 and on += and ++ from BEG-010.

Learning Objectives

By the end of this lesson you will be able to:

  • Write a for loop with the shape for (start; condition; update) { body }.
  • Count up, count down, and step by a value other than one.
  • Choose between < and <= to get the exact count you want.
  • Trace a loop with a table of variable values.
  • State the scope of a loop variable declared in the for header.
  • Use a loop to accumulate a sum or a repeated calculation.

Written Explanation

The shape

java
for (int i = 1; i <= 5; i++) {
    // body
}
SlotExampleWhen it runs
Startint i = 1Once, before anything else
Conditioni <= 5Before every iteration, including the first
Updatei++After every iteration, before the next check

The two semicolons inside the parentheses separate the three slots. The Java Tutorials call the slots initialization, termination expression, and increment; this course says start, condition, update.

Counting up and down

  • Up by one: for (int i = 1; i <= 5; i++) gives 1, 2, 3, 4, 5.
  • Down by one: for (int i = 5; i >= 1; i--) gives 5, 4, 3, 2, 1. Notice that the condition flips from <= to >=: when counting down you keep going while i is still at least the last value.
  • By a step: for (int i = 0; i <= 10; i += 2) gives 0, 2, 4, 6, 8, 10.

The update can be any statement that changes the counter: i++, i--, i += 3, even i *= 2.

The count: < versus <=

Two loops that look alike produce different counts:

LoopValues of iRuns
for (int i = 1; i <= 5; i++)1, 2, 3, 4, 55
for (int i = 0; i < 5; i++)0, 1, 2, 3, 45
for (int i = 1; i < 5; i++)1, 2, 3, 44

A handy rule: with a start a and an end b, a loop with i <= b runs b - a + 1 times, and with i < b it runs b - a times (when step is 1). Programmers often count from 0 with <, because "0 up to but not including n" runs exactly n times. You will see that pattern constantly.

Tracing a loop

To trace, make a table with a column for each variable and a row for each iteration. Here is the sum of 1 to 5:

java
int sum = 0;
for (int i = 1; i <= 5; i++) {
    sum += i;
}
CheckiCondition i <= 5sum after body
11true1
22true3
33true6
44true10
55true15
66falseloop ends

The last row is important: i becomes 6 and the check fails. In every counting loop, the counter finishes past the last value. That is why, after the loop, i is not 5.

The scope of the loop variable

A variable declared in the for header, such as int i, exists only inside the loop. The Java Tutorials say its scope runs from the declaration to the end of the block the for governs. After the closing brace, i is gone, and using it is a compile error. This is a feature: the counter cannot leak into later code. If you need the final value after the loop, declare the variable before it:

java
int i;
for (i = 1; i <= 5; i++) { }
// i is 6 here

Prefer the usual form unless you really need the value afterwards.

Do not touch the counter in the body

The update slot is the loop's place for changing the counter. If you also change i inside the body, the loop skips values or never ends, and the code is hard to read. We return to this in L06.

Examples

Example 1: sum of 1 to 5 with a trace (simple)

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

Output:

text
i=1 sum=1
i=2 sum=3
i=3 sum=6
i=4 sum=10
i=5 sum=15

This printed trace matches the table above. Printing the counter and the accumulator inside the body is a quick way to check any loop.

Example 2: counting down by 3 (practical)

java
for (int i = 10; i >= 1; i -= 3) {
    System.out.print(i + " ");
}
System.out.println();

Output:

text
10 7 4 1 

The values are 10, 7, 4, 1. The next would be -2, which fails i >= 1, so the loop ends. System.out.print (without ln) keeps the values on one line.

Example 3: growing a balance (realistic)

A savings account earns 5 percent a year, added to the balance each year. This loop shows the balance for three years (an illustration of the idea, not financial advice):

java
double balance = 1000;
for (int year = 1; year <= 3; year++) {
    balance = balance * 1.05;
    System.out.printf("Year %d: %.2f%n", year, balance);
}

Output:

text
Year 1: 1050.00
Year 2: 1102.50
Year 3: 1157.63

Each iteration uses the result of the one before it: the balance is both read and written. The format codes come from BEG-011-L04: %d for an integer, %.2f for two decimal places, %n for a new line.

Backend Insight

Counting loops appear wherever a program deals with ranges: page numbers (pages 1 to N of search results), retry attempts (try up to 3 times), batches (process 100 items at a time), and time windows. A few habits pay off immediately:

  • Name the end value. for (int attempt = 1; attempt <= maxAttempts; attempt++) documents itself; <= 3 does not.
  • Keep the body short. If the body grows long, move it into a method (you will learn those soon) and call it.
  • Know the count before running. If you can say "this runs n times", you can also reason about its cost, which is the start of the complexity work in BEG-039.

Common Mistakes

Mistake 1: Using < when you meant <=

  • Incorrect: for (int i = 1; i < 10; i++) when you wanted 1 to 10. It stops at 9.
  • Correct: for (int i = 1; i <= 10; i++).

Always ask: "Is the last value included?"

Mistake 2: A condition that does not match the direction

java
for (int i = 10; i <= 1; i--) { }

The condition 10 <= 1 is false immediately, so the body never runs. When counting down, use >=.

Mistake 3: A semicolon after the header

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

The ; is an empty body. The loop spins three times doing nothing, then Hello prints once. Never put a semicolon after the closing parenthesis.

Mistake 4: Using the loop variable after the loop

i is out of scope after the closing brace, so the compiler reports a "cannot find symbol" style error. Declare it before the loop if you need it.

Mistake 5: Changing the counter in the body

Adding i++ in the body of a loop that already has i++ in the header makes the counter jump by two. Use one place for the update.

Exercises

Try each exercise yourself before opening the solutions.

Level A: Foundation

A1. List the values of i: for (int i = 2; i <= 10; i += 4).

Show solution A1

A1. 2, 6, 10. The next value would be 14, which fails the condition.

A2. How many times does for (int i = 0; i < 7; i++) run? How many for i <= 7?

Show solution A2

A2. 7 times (values 0 to 6) and 8 times (values 0 to 7).

A3. Write the header of a loop that counts from 20 down to 5 in steps of 5.

Show solution A3

A3. for (int i = 20; i >= 5; i -= 5), giving 20, 15, 10, 5.

Level B: Application

B1. Write a loop that computes the sum of the even numbers from 2 to 20 and prints the result.

Show solution B1

B1.

java
int sum = 0;
for (int i = 2; i <= 20; i += 2) {
    sum += i;
}
System.out.println(sum);   // 110

B2. Complete the trace table for this loop: int p = 1; for (int i = 1; i <= 4; i++) { p *= 2; }. Give i and p after each iteration, and the final p.

Show solution B2

B2. After iteration 1: i=1, p=2; 2: i=2, p=4; 3: i=3, p=8; 4: i=4, p=16. Final p is 16 (the loop computes 2 to the power 4).

B3. The loop below should print 1 to 5 but prints nothing. Fix it.

java
for (int i = 1; i > 5; i++) {
    System.out.println(i);
}
Show solution B3

B3. The condition i > 5 is false at the start. Use i <= 5.

Level C: Challenge

C1. Print the first 10 values of a savings plan: start with 100, add 20 each month, and print the total after each month.

Show solution C1

C1.

java
int total = 100;
for (int month = 1; month <= 10; month++) {
    total += 20;
    System.out.println("Month " + month + ": " + total);
}

C2. Without running it, say what this prints and why:

java
for (int i = 0; i < 6; i++) {
    System.out.print(i + " ");
    i++;
}
Show solution C2

C2. It prints 0 2 4 . The header adds 1 and the body adds another 1, so i goes 0, 2, 4, 6 and the check 6 < 6 fails. This is the "counter changed in two places" mistake.

Mini Challenge

Write a program that prints a multiplication table for one number. Store the number in an int variable (for example 7). The loop must print lines like 7 x 1 = 7 up to 7 x 10 = 70.

Then change the loop so that it prints only the lines for odd multipliers (1, 3, 5, 7, 9) by changing the update, not by adding an if.

Check your work: the first version prints 10 lines, the second prints 5, and changing the number variable changes every line.

Summary & Next Lesson

Key takeaways

  • A for loop has the shape for (start; condition; update) { body }; use it when the count is known.
  • i++, i--, and i += n are the common updates; the condition must match the direction.
  • <= includes the last value, < excludes it. Starting at 0 with < runs exactly n times.
  • Trace a loop with a table; the counter ends past the last value.
  • A variable declared in the header lives only inside the loop.

Next lesson

The next lesson, "while and do-while", covers loops where you do not know the count in advance, such as asking until the input is valid.

Self-check

  1. In which order do start, condition, and update run?
  2. How many times does for (int i = 3; i <= 8; i++) run?
  3. What condition do you use to count down to 1?
  4. Why does for (...); with a semicolon before the braces cause trouble?
  5. What is the value of i that makes for (int i = 1; i <= 5; i++) stop?
Show answers
  1. Start once; then condition, body, update; then condition again.
  2. 6 times (3, 4, 5, 6, 7, 8).
  3. i >= 1.
  4. The semicolon is an empty body, so the loop does nothing and the braces run once afterwards.
  5. 6, the first value for which i <= 5 is false.

References

  • Oracle, The for Statement (Java Tutorials). It supports the three expressions, the descending and i++ examples, and the scope of a variable declared in the initialization.
  • Oracle, Java Language Specification, SE 21, Chapter 14. It supports the order in which the start, condition, body, and update run. The trace tables and the < versus <= counts were checked by compiling and running the examples with JDK 21.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.