Programming and Java Fundamentals

For Loops

ReadingPreview

You are viewing a free preview lesson.

For Loops

Lesson Overview

In a program, we often need to perform the same task multiple times.

For example:

  • Print numbers from 1 to 10
  • Display a message several times
  • Add several values
  • Create a multiplication table
  • Read every character of a String

Instead of manually writing the same statement repeatedly, Java provides loops.

When the number of repetitions is known in advance or iteration is controlled using a counter, a for loop is very useful.

In this lesson, we will learn:

  • Loops and iterations
  • for loop syntax
  • Initialization, condition, and update
  • Forward and backward counting
  • Custom step sizes
  • Accumulators
  • Even and odd numbers
  • Multiplication tables
  • String traversal
  • Nested loops
  • Infinite loops
  • Off-by-one errors

Learning Objectives

After completing this lesson, you will be able to:

  • Explain loops and iterations
  • Write a basic for loop
  • Understand initialization, condition, and update
  • Count forward and backward
  • Use custom step sizes
  • Calculate sums and counts using loops
  • Iterate through String characters
  • Understand basic nested loops
  • Identify infinite loops and off-by-one errors

What Is a Loop?

A loop is a control-flow structure that executes a block of code multiple times.

Without a loop:

System.out.println("Java");
System.out.println("Java");
System.out.println("Java");

Using a loop:

for (int count = 1; count <= 3; count++) {
    System.out.println("Java");
}

Output:

Java
Java
Java

What Is an Iteration?

Each execution of the loop body is called an iteration.

for (int count = 1; count <= 3; count++) {
    System.out.println(count);
}

There are three iterations:

Iteration 1 → count = 1
Iteration 2 → count = 2
Iteration 3 → count = 3

Output:

1
2
3

Basic for Loop Syntax

for (initialization; condition; update) {
    // Repeated statements
}

Example:

for (int number = 1; number <= 5; number++) {
    System.out.println(number);
}

A basic for loop has three parts:

  1. Initialization
  2. Condition
  3. Update

Initialization

int number = 1

This executes once before the loop begins.

Here, the counter starts at 1.

Condition

number <= 5

The condition is checked before every iteration.

  • If it is true, the loop body executes
  • If it is false, the loop ends

Update

number++

This executes after every iteration.

Here, number increases by 1 after each iteration.

Execution Flow

for (int number = 1; number <= 3; number++) {
    System.out.println(number);
}

Execution:

number = 1
1 <= 3 → true
Print 1
number becomes 2

2 <= 3 → true
Print 2
number becomes 3

3 <= 3 → true
Print 3
number becomes 4

4 <= 3 → false
Stop

Output:

1
2
3

Loop Counter

A variable used to control a loop is called a counter.

for (int count = 1; count <= 5; count++) {
    System.out.println(count);
}

Here:

count

is the counter.

For small index-based loops, i is conventional:

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

When the meaning is important, use a descriptive name:

for (
        int lessonNumber = 1;
        lessonNumber <= 5;
        lessonNumber++
) {
    System.out.println(
            "Lesson " + lessonNumber
    );
}

Forward Counting

for (int number = 1; number <= 5; number++) {
    System.out.println(number);
}

Output:

1
2
3
4
5

Counting from Zero

In programming, indexes often start from 0.

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

Output:

0
1
2
3
4

The loop executes five times.

< vs. <=

for (int number = 1; number < 5; number++) {
    System.out.println(number);
}

Output:

1
2
3
4

But:

for (int number = 1; number <= 5; number++) {
    System.out.println(number);
}

Output:

1
2
3
4
5

Difference:

< 5  → 5 excluded
<= 5 → 5 included

Backward Counting

Use -- to decrease the counter.

for (int number = 5; number >= 1; number--) {
    System.out.println(number);
}

Output:

5
4
3
2
1

Countdown

for (int second = 5; second >= 1; second--) {
    System.out.println(second);
}

System.out.println("Start");

Output:

5
4
3
2
1
Start

Custom Step Size

The counter does not need to change by exactly 1 on every iteration.

Increase by Two

for (int number = 0; number <= 10; number += 2) {
    System.out.println(number);
}

Output:

0
2
4
6
8
10

Increase by Five

for (int number = 5; number <= 25; number += 5) {
    System.out.println(number);
}

Output:

5
10
15
20
25

Decrease by Two

for (int number = 10; number >= 0; number -= 2) {
    System.out.println(number);
}

Output:

10
8
6
4
2
0

Printing Even Numbers

You can iterate through every number and check a condition:

for (int number = 1; number <= 10; number++) {
    if (number % 2 == 0) {
        System.out.println(number);
    }
}

Output:

2
4
6
8
10

But when the pattern is already known:

for (int number = 2; number <= 10; number += 2) {
    System.out.println(number);
}

is more direct.

Printing Odd Numbers

for (int number = 1; number <= 10; number += 2) {
    System.out.println(number);
}

Output:

1
3
5
7
9

Accumulator

A variable can be used to collect results across loop iterations.

This is called an accumulator.

int total = 0;

for (int number = 1; number <= 5; number++) {
    total += number;
}

System.out.println(total);

Output:

15

Calculation:

0 + 1 = 1
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
10 + 5 = 15

Why Does a Sum Accumulator Start at 0?

For addition:

0 + number = number

Therefore, a sum accumulator generally starts with:

int total = 0;

Counting Matching Values

An accumulator can be used not only for sums but also for counting.

int evenCount = 0;

for (int number = 1; number <= 10; number++) {
    if (number % 2 == 0) {
        evenCount++;
    }
}

System.out.println(
        "Even numbers: " + evenCount
);

Output:

Even numbers: 5

Sum of Even Numbers

int total = 0;

for (int number = 2; number <= 10; number += 2) {
    total += number;
}

System.out.println(total);

Output:

30

Multiplication Table

int number = 5;

for (
        int multiplier = 1;
        multiplier <= 10;
        multiplier++
) {
    int result =
            number * multiplier;

    System.out.println(
            number
            + " × "
            + multiplier
            + " = "
            + result
    );
}

Output:

5 × 1 = 5
5 × 2 = 10
5 × 3 = 15
5 × 4 = 20
5 × 5 = 25
5 × 6 = 30
5 × 7 = 35
5 × 8 = 40
5 × 9 = 45
5 × 10 = 50

Calculating an Average

int total = 0;
int numberCount = 5;

for (
        int number = 1;
        number <= numberCount;
        number++
) {
    total += number;
}

double average =
        total / (double) numberCount;

System.out.println(
        "Average: " + average
);

Output:

Average: 3.0

Iterating Through String Characters

String characters can be accessed by index.

String language = "Java";

for (
        int index = 0;
        index < language.length();
        index++
) {
    char character =
            language.charAt(index);

    System.out.println(character);
}

Output:

J
a
v
a

Why Use < length()?

String:

Java

Length:

4

Valid indexes:

0
1
2
3

Therefore:

index < language.length()

is correct.

Wrong:

index <= language.length()

because on the last iteration, the index becomes 4, and:

language.charAt(4)

is not valid.

Printing Index and Character

String word = "Loop";

for (
        int index = 0;
        index < word.length();
        index++
) {
    System.out.println(
            index
            + ": "
            + word.charAt(index)
    );
}

Output:

0: L
1: o
2: o
3: p

Counting a Character

String value = "Java Foundation";
int aCount = 0;

for (
        int index = 0;
        index < value.length();
        index++
) {
    char character =
            value.charAt(index);

    if (
            character == 'a'
            || character == 'A'
    ) {
        aCount++;
    }
}

System.out.println(
        "A count: " + aCount
);

Output:

A count: 3

Nested for Loop

A loop inside another loop is called a nested loop.

for (int row = 1; row <= 3; row++) {
    for (int column = 1; column <= 2; column++) {
        System.out.println(
                "Row "
                + row
                + ", Column "
                + column
        );
    }
}

Output:

Row 1, Column 1
Row 1, Column 2
Row 2, Column 1
Row 2, Column 2
Row 3, Column 1
Row 3, Column 2

How Does a Nested Loop Work?

For each iteration of the outer loop, the inner loop runs through its complete cycle.

row = 1
    column = 1
    column = 2

row = 2
    column = 1
    column = 2

row = 3
    column = 1
    column = 2

Total inner executions:

3 × 2 = 6

Simple Rectangle Pattern

for (int row = 1; row <= 3; row++) {
    for (int column = 1; column <= 4; column++) {
        System.out.print("*");
    }

    System.out.println();
}

Output:

****
****
****

Nested loops are commonly useful for understanding grids, tables, or two-dimensional repetition.

Loop Variable Scope

A counter declared inside the loop header is not accessible outside the loop.

for (int number = 1; number <= 5; number++) {
    System.out.println(number);
}

Outside this loop:

System.out.println(number);

is not valid.

If the counter is needed only for the loop, it is better to declare it inside the loop header.

Infinite Loop

A loop that does not naturally terminate is called an infinite loop.

Accidental example:

for (int number = 1; number <= 5; number--) {
    System.out.println(number);
}

The counter becomes:

1
0
-1
-2
...

The condition:

number <= 5

does not become false.

Correct:

for (int number = 1; number <= 5; number++) {
    System.out.println(number);
}

Wrong Direction in a Backward Loop

Wrong:

for (int number = 5; number >= 1; number++) {
    System.out.println(number);
}

The counter keeps increasing.

Correct:

for (int number = 5; number >= 1; number--) {
    System.out.println(number);
}

Off-by-One Error

When a loop executes one time more or one time fewer than expected, it is called an off-by-one error.

Expected:

1
2
3
4
5

Wrong:

for (int number = 1; number < 5; number++) {
    System.out.println(number);
}

Output:

1
2
3
4

Correct:

number <= 5

Off-by-One Error with String Indexes

Wrong:

String word = "Java";

for (
        int index = 0;
        index <= word.length();
        index++
) {
    System.out.println(
            word.charAt(index)
    );
}

On the final iteration:

index = 4

But the last valid index is:

3

Correct:

index < word.length()

Extra Semicolon After for

Wrong:

for (int number = 1; number <= 5; number++); {
    System.out.println("Java");
}

The semicolon creates an empty loop body.

Correct:

for (int number = 1; number <= 5; number++) {
    System.out.println("Java");
}

Updating the Counter Again Inside the Body

Confusing:

for (int number = 1; number <= 10; number++) {
    System.out.println(number);

    number++;
}

The counter increases twice during every iteration.

Output:

1
3
5
7
9

If you want to increase by two, make the intent clear in the loop header:

for (
        int number = 1;
        number <= 10;
        number += 2
) {
    System.out.println(number);
}

Tracing a Loop

When understanding or debugging a loop, it can be useful to write down the values for every iteration.

int total = 0;

for (int number = 1; number <= 3; number++) {
    total += number;
}

Trace:

Iterationnumbertotal beforetotal after
1101
2213
3336

Final:

total = 6

Complete Example

public class Main {

    public static void main(String[] args) {
        int total = 0;
        int evenCount = 0;

        for (
                int number = 1;
                number <= 10;
                number++
        ) {
            total += number;

            if (number % 2 == 0) {
                evenCount++;
            }
        }

        double average =
                total / 10.0;

        System.out.println(
                "Total: " + total
        );

        System.out.println(
                "Average: " + average
        );

        System.out.println(
                "Even numbers: "
                + evenCount
        );
    }
}

Output:

Total: 55
Average: 5.5
Even numbers: 5

When Should You Use a for Loop?

A for loop is a good choice when:

  • The repetition count is known
  • The start and end are known
  • A counter is needed
  • A numeric range needs to be iterated
  • String indexes need to be traversed
  • A fixed number of repetitions is required

Examples:

Print 1–100
Repeat a message 5 times
Read each String index
Generate a multiplication table

Important Terms

Loop

Executes a block of code multiple times.

Iteration

One execution of the loop body.

Initialization

Creates the initial state before the loop begins.

Condition

Determines whether the loop should continue.

Update

Changes the counter after each iteration.

Counter

A variable used to control a loop.

Accumulator

Collects results across iterations.

Nested Loop

A loop inside another loop.

Infinite Loop

A loop that does not terminate as expected.

Off-by-One Error

An error where an incorrect boundary causes a loop to execute one time too many or one time too few.

Practice Exercise 1: Print 1 to 10

Use a for loop to print:

1
2
3
4
5
6
7
8
9
10

Practice Exercise 2: Reverse Counting

Print from 10 down to 1.

Practice Exercise 3: Even Numbers

Print the even numbers from 1 to 20.

Practice Exercise 4: Odd Numbers

Print the odd numbers from 1 to 20.

Practice Exercise 5: Sum

Calculate the sum of the numbers from 1 to 100.

Expected:

5050

Practice Exercise 6: Multiplication Table

Print the multiplication table of a number from 1 to 10.

Practice Exercise 7: Character Traversal

String word = "Java";

Print each character on a separate line.

Practice Exercise 8: Count a Character

String text = "Java Foundation";

Count how many times a or A appears.

Practice Exercise 9: Rectangle

Use a nested loop to create:

****
****
****

Practice Exercise 10: Fix the Loop

for (
        int number = 1;
        number <= 10;
        number--
) {
    System.out.println(number);
}

Explain why the loop does not end and fix it.

Practice Exercise 11: Fix the Index

String text = "Java";

for (
        int index = 0;
        index <= text.length();
        index++
) {
    System.out.println(
            text.charAt(index)
    );
}

Fix the error.

Practice Exercise 12: Trace the Loop

int total = 0;

for (
        int number = 2;
        number <= 8;
        number += 2
) {
    total += number;
}

Write the value of:

  • number
  • total

for each iteration.

Knowledge Check

Question 1

What is a loop?

Question 2

What is an iteration?

Question 3

What are the three main parts of a for loop?

Question 4

How many times does initialization execute?

Question 5

When is the condition checked?

Question 6

When does the update execute?

Question 7

What does number++ do?

Question 8

What does number += 2 do?

Question 9

What is the difference between < and <=?

Question 10

What is generally used for backward counting?

Question 11

What is an accumulator?

Question 12

What value does a sum accumulator generally start with?

Question 13

What is the last valid index of a String?

Question 14

What is a common condition for traversing a String?

Question 15

What is a nested loop?

Question 16

If the outer loop executes 3 times and the inner loop executes 2 times for each outer iteration, how many times does the inner body execute in total?

Question 17

What is an infinite loop?

Question 18

What is an off-by-one error?

Knowledge Check Answers

Answer 1

A loop is a control-flow structure that executes a block of code multiple times.

Answer 2

Each execution of the loop body is an iteration.

Answer 3

  • Initialization
  • Condition
  • Update

Answer 4

Once, before the loop starts.

Answer 5

Before every iteration.

Answer 6

After the body of each successful iteration executes.

Answer 7

It increases the variable's value by 1.

Answer 8

It increases the variable's value by 2.

Answer 9

< limit excludes the limit, while <= limit includes the limit.

Answer 10

Usually decrement:

number--

Answer 11

A variable used to collect or update a result while loop iterations execute.

Answer 12

0

Answer 13

text.length() - 1

Answer 14

index < text.length()

Answer 15

A loop inside another loop.

Answer 16

3 × 2 = 6

Answer 17

A loop that does not terminate as expected.

Answer 18

An error where an incorrect boundary condition causes a loop to execute one time more or one time fewer than expected.

Lesson Summary

In this lesson, we learned:

  • Loops execute repeated code
  • Each execution is an iteration
  • A for loop consists of initialization, condition, and update
  • Initialization executes once
  • The condition is checked before each iteration
  • The update executes after the loop body
  • A counter can move forward or backward
  • Custom step sizes can be used
  • < and <= change loop boundaries
  • An accumulator can collect a sum or count
  • Even and odd numbers can be processed using loops
  • Multiplication tables can be generated
  • String characters can be iterated using indexes
  • String traversal commonly uses index < length()
  • Nested loops handle two levels of repetition
  • Incorrect conditions or update directions can create infinite loops
  • Boundary mistakes can create off-by-one errors
  • A counter should not be modified unnecessarily inside the loop body
  • Trace tables help understand and debug loops