Lesson 17 / 140

Lesson access পরীক্ষা করা হচ্ছে...

Video এবং লিখিত lesson · 26 মিনিট

For Loops

Repeat work with `for` loops: count up and down, sum values, walk through a String, nest loops and avoid off-by-one errors.

PreviewCaptionsশীঘ্রই

আপনি একটি free preview lesson দেখছেন।

Lesson Overview

Programs often do the same task many times: print the numbers from 1 to 10, add up a list of values, build a multiplication table, look at every character of a String. Writing the same statement again and again does not scale, and it cannot handle a count that is only known while the program runs.

Java provides loops for this. When the number of repetitions is known in advance or controlled by a counter, a for loop is the natural choice. Loops are also where two classic bugs appear, loops that never end and loops that run one time too many or too few, so we will learn to spot both.

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:

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

Using a loop:

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

Output:

text
Java
Java
Java

What Is an Iteration?

Each execution of the loop body is called an iteration. The loop above has three iterations, one for each value of count: 1, 2 and 3.

Basic for Loop Syntax

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

Example:

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

A basic for loop has three parts:

  1. Initialization — int number = 1 executes once before the loop begins. Here, the counter starts at 1.
  2. Condition — number <= 5 is checked before every iteration. If it is true, the loop body executes; if it is false, the loop ends.
  3. Update — number++ executes after every iteration. Here, number increases by 1 after each iteration.

Execution Flow

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

Execution:

text
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:

text
1
2
3

Loop Counter

A variable used to control a loop, such as number above, is called a counter. For small index-based loops, i is conventional:

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

When the meaning is important, use a descriptive name:

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

Counting Forward and Backward

Counting from Zero

In programming, indexes often start from 0. This loop executes five times:

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

Output:

text
0
1
2
3
4

< vs. <=

The loop in Basic for Loop Syntax uses number <= 5 and prints 1 to 5. With <, the last value is left out:

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

Output:

text
1
2
3
4

Difference:

text
< 5  → 5 excluded
<= 5 → 5 included

Backward Counting

Use -- to decrease the counter. Start at the high value and keep going while the counter is >= the low value:

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

Output:

text
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

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

Output:

text
0
2
4
6
8
10

Decrease by Two

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

Output:

text
10
8
6
4
2
0

Even and Odd Numbers

You can iterate through every number and check a condition:

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

Output:

text
2
4
6
8
10

But when the pattern is already known, stepping by two is more direct: for (int number = 2; number <= 10; number += 2) prints the same numbers without checking each one. Odd numbers work the same way, starting from 1:

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

Output:

text
1
3
5
7
9

Accumulator

A variable can be used to collect results across loop iterations. This is called an accumulator.

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

Output:

text
15

On each iteration total grows by the current number: 0 + 1 = 1, 1 + 2 = 3, and so on up to 10 + 5 = 15 (Tracing a Loop below shows how to write this down as a table).

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.

java
int evenCount = 0;
for (int number = 1; number <= 10; number++) {
    if (number % 2 == 0) {
        evenCount++;
    }
}
System.out.println("Even numbers: " + evenCount);

Output:

text
Even numbers: 5

More Loop Examples

Multiplication Table

java
int number = 5;
for (int multiplier = 1; multiplier <= 10; multiplier++) {
    int result = number * multiplier;
    System.out.println(number + " × " + multiplier + " = " + result);
}

Output:

text
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

java
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:

text
Average: 3.0

Iterating Through String Characters

String characters can be accessed by index:

java
String language = "Java";
for (int index = 0; index < language.length(); index++) {
    char character = language.charAt(index);
    System.out.println(character);
}

Output:

text
J
a
v
a

Why Use < length()?

The String Java has length 4, so its valid indexes are 0, 1, 2 and 3. Therefore, index < language.length() is correct. index <= language.length() is wrong, because on the last iteration the index becomes 4, and language.charAt(4) is not valid.

Printing Index and Character

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

Output:

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

Counting a Character

java
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:

text
A count: 3

Nested for Loop

A loop inside another loop is called a nested loop.

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

Output:

text
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, so the inner body executes 3 × 2 = 6 times in total:

text
row = 1
    column = 1
    column = 2

row = 2
    column = 1
    column = 2

row = 3
    column = 1
    column = 2

Simple Rectangle Pattern

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

Output:

text
****
****
****

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.

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

Tracing a Loop

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

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

Trace:

Iterationnumbertotal beforetotal after
1101
2213
3336

Final: total = 6.

Complete Example

java
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:

text
Total: 55
Average: 5.5
Even numbers: 5

When Should You Use a for Loop?

A for loop is a good choice when the start and end are known and a counter drives the repetition: printing 1 to 100, repeating a message five times, visiting each String index, generating a multiplication table. When the number of repetitions depends on something that happens inside the loop, such as user input, the while loop of the next lesson fits better.

Predict the Result

Question 1

java
for (int number = 0; number < 10; number += 3) {
    System.out.print(number + " ");
}

What does this print?

Answer

0 3 6 9 . The update adds 3 each time. After 9 the variable becomes 12, the condition 12 < 10 is false, and the loop stops.

Question 2

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

What does this print?

Answer

6. The loop runs for 0, 1, 2, 3, 4 and 5. Starting at 0 and using <= adds one iteration; i < 5 would run five times.

Question 3

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

What does this print?

Answer

text
*
**
***

The inner loop's condition uses row, so it runs once in the first row, twice in the second and three times in the third.

Question 4

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

Will it compile?

Answer

No: cannot find symbol for i in the last line. A variable declared in the for header exists only inside the loop. Declare it before the loop if you need it afterwards.

Common Mistakes

Infinite Loop

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

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

The counter becomes:

text
1
0
-1
-2
...

The condition number <= 5 does not become false in any reasonable time. (After about two billion iterations, the int counter overflows, as you saw in lesson 1.10, and wraps to a large positive value. That is still a bug, not a way to end a loop.) The fix is the update number++.

The same happens in a backward loop written with number++ instead of number--: the counter moves away from the end condition. Check that the update moves the counter toward the point where the condition becomes false.

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. If the expected output is 1 to 5, number < 5 stops at 4 (see < vs. <=); the fix is number <= 5.

With String indexes the mistake goes the other way: index <= word.length() runs one time too many, and on the last iteration word.charAt(4) fails for "Java", whose last valid index is 3. Use index < word.length().

Extra Semicolon After for

Wrong:

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

The semicolon creates an empty loop body. The loop runs five times doing nothing, and then the block below it runs once, so Java is printed only once. Correct:

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

Updating the Counter Again Inside the Body

Confusing:

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

The counter increases twice during every iteration.

Output:

text
1
3
5
7
9

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

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

Practice Exercise 1: Print 1 to 10

Solutions: lesson 1.25.

Use a for loop to print:

text
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

For String word = "Java";, print each character on a separate line.

Practice Exercise 8: Count a Character

For String text = "Java Foundation";, count how many times a or A appears.

Practice Exercise 9: Rectangle

Use a nested loop to create:

text
****
****
****

Practice Exercise 10: Fix the Loop

java
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

java
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

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

Write the value of number and 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

  • A loop executes a block of code multiple times, and each execution of the body is an iteration.
  • A for loop has three parts: initialization runs once, the condition is checked before every iteration, and the update runs after every iteration.
  • The counter can count forward, backward, or with a custom step such as += 2.
  • An accumulator collects a result across iterations; a sum accumulator starts at 0.
  • To traverse a String, use index < text.length(), because the last valid index is length() - 1.
  • In a nested loop, the inner loop runs through its complete cycle for each iteration of the outer loop.
  • A counter that moves in the wrong direction causes an infinite loop, and a wrong boundary (< vs. <=) causes an off-by-one error.

আগে ভাবুন

শীঘ্রই আসছে

Checkpoint প্রশ্ন, যেখানে lesson উত্তর দেখানোর আগে আপনাকে একটি উত্তর বেছে নিতে হবে।