# Loops

Course: [Java](https://www.devtutorials.ai/learn/java) · Section: Control Flow
Source: https://www.devtutorials.ai/learn/java/control-flow/loops

> Repeat code with for, while and do-while loops, nest loops, control them with break and continue, and avoid infinite loops.

Think of climbing stairs.

You place one foot on a step, then the other. You keep going the same way until there are no steps left.

That is what a loop does in programming. It repeats a block of code again and again until a condition tells it to stop.

In simple terms: a loop lets you write code once and run it many times.

## What You Will Learn

In this lesson, you will learn:

1. Why loops are useful and how they work step by step.
2. The difference between entry-controlled and exit-controlled loops.
3. How to write `for`, `while`, and `do-while` loops.
4. How to nest one loop inside another.
5. How `break` and `continue` change loop flow.
6. What an infinite loop is and how to avoid one by accident.
7. How to choose the right loop for a task.

## Start With a Working Example

Press **Run**.

```java runnable title="Three lines of code print five lines of output"
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Push-up number " + i);
        }
        System.out.println("Workout done!");
    }
}
```

Expected output:

```text
Push-up number 1
Push-up number 2
Push-up number 3
Push-up number 4
Push-up number 5
Workout done!
```

The `println` statement is written once. The loop runs it five times. Each time, `i` increases by one.

### Try This

Change `5` to `10`. You will get ten lines without adding another `println`.

## Loop Fundamentals

### Why Loops Are Needed

Imagine printing the numbers 1 to 100. Without a loop, you would need 100 `println` statements.

That causes three problems:

- It takes time to write.
- A small change means editing many lines.
- It does not scale when you do not know the data size in advance.

A loop solves all three. You write the code once, and the loop decides how many times to repeat it.

### Repetition in Programming

Repeating a task is one of the most common things a program does:

- adding up every price in a shopping cart;
- sending a reminder to every student in a class;
- asking for a password until the user gets it right;
- updating a game scene on every frame.

Each run of a loop body is called an **iteration**. If a loop runs five times, it has five iterations.

### Execution Flow

Java usually runs code from top to bottom, one line at a time. A loop changes that flow. After the loop body finishes, Java jumps back to the condition and checks again.

### Loop Execution Flow

Every loop follows the same basic pattern:

1. **Start:** set up a counter or starting value.
2. **Check:** test the condition.
3. **Run:** if the condition is true, execute the loop body.
4. **Update:** change the counter, then repeat from step 2.

When the check becomes `false`, the loop ends and Java continues with the next line after the loop.

```text
   start
     │
     ▼
 ┌─► check ── false ──► leave the loop
 │     │
 │   true
 │     ▼
 │   run the body
 │     │
 │     ▼
 └── update
```

### Entry-Controlled vs Exit-Controlled Loops

Loops are grouped by **when** they check the condition.

- An **entry-controlled** loop checks the condition before each run. If the condition is false from the start, the body never runs. `for` and `while` are entry-controlled.
- An **exit-controlled** loop checks the condition after each run. The body always runs at least once. `do-while` is exit-controlled.

Think of a nightclub. An entry-controlled loop checks your ID before you enter. An exit-controlled loop checks it on the way out.

### Choosing the Right Loop

| Loop | Use it when | Example |
|---|---|---|
| `for` | You know how many times to repeat | Print a times table up to 10 |
| `while` | You repeat until something happens, and the count is unknown | Keep reading until the user types "quit" |
| `do-while` | The body must run at least once | Show a menu, then ask whether to show it again |

**Easy Way to Remember:** **for** = you know the count. **while** = you wait for a condition. **do-while** = do it once, then decide.

## for Loop

### Definition and Structure

A `for` loop puts the start, condition, and update in one place.

```text
for (start; condition; update) {
    // loop body
}
```

- **start** runs once before the loop begins. It usually creates a counter: `int i = 1`.
- **condition** is checked before every iteration: `i <= 5`.
- **update** runs after every iteration: `i++`.

The counter is often named `i`, but any valid variable name works.

### Control Flow

Here is a `for` loop that counts down:

```java runnable title="A for loop counts down from 5"
public class Main {
    public static void main(String[] args) {
        for (int seconds = 5; seconds >= 1; seconds--) {
            System.out.println(seconds + "...");
        }
        System.out.println("Lift off!");
    }
}
```

Expected output:

```text
5...
4...
3...
2...
1...
Lift off!
```

Step by step:

1. `seconds` starts at `5`.
2. `5 >= 1` is true, so the body prints `5...`.
3. `seconds--` changes it to `4`.
4. The loop keeps going until `seconds` becomes `0`.
5. `0 >= 1` is false, so the loop ends and `Lift off!` prints.

The counter exists only inside the loop. After the closing brace, `seconds` is out of scope.

### Adding Up Values

A very common use of a loop is building a total.

```java runnable title="A loop adds up the numbers 1 to 10"
public class Main {
    public static void main(String[] args) {
        int sum = 0;

        for (int n = 1; n <= 10; n++) {
            sum += n;
        }

        System.out.println("Sum of 1 to 10: " + sum);
    }
}
```

Expected output:

```text
Sum of 1 to 10: 55
```

`sum` starts at `0`. Each iteration adds the current number to it. After ten iterations, `sum` holds `55`.

Notice that `sum` is declared before the loop. If it were declared inside the loop, it would reset to `0` every time.

A variable created in the `for` header, like `int n = 1`, only exists inside the loop. If you need the final value after the loop, declare it before the loop instead.

### Looping Over an Array

A `for` loop is a natural fit for arrays because the index runs from `0` to `length - 1`.

```java runnable title="A for loop visits every item in an array"
public class Main {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Mango", "Banana"};

        for (int i = 0; i < fruits.length; i++) {
            System.out.println((i + 1) + ". " + fruits[i]);
        }
    }
}
```

Expected output:

```text
1. Apple
2. Mango
3. Banana
```

The condition is `i < fruits.length`, not `<=`. The last valid index is `2`, while `fruits.length` is `3`.

Java also has a shorter **for-each** loop for this task: `for (String fruit : fruits)`. It visits each item without using an index.

### Nested for Loop

A **nested loop** is a loop inside another loop.

For every iteration of the outer loop, the inner loop runs all of its iterations.

Think of a clock. The minute hand goes all the way around once for every step of the hour hand.

```java runnable title="The inner loop finishes fully for each outer step"
public class Main {
    public static void main(String[] args) {
        for (int row = 1; row <= 3; row++) {
            for (int col = 1; col <= 4; col++) {
                System.out.print(row * col + "\t");
            }
            System.out.println();
        }
    }
}
```

Expected output:

```text
1	2	3	4
2	4	6	8
3	6	9	12
```

The outer loop runs 3 times. Each time, the inner loop runs 4 times. So the body runs 3 × 4 = 12 times.

`print` keeps the numbers on one line. `\t` adds a tab between them. The `println()` after the inner loop ends each row.

Nested loops are useful for grids, tables, seat maps, and patterns.

```java runnable title="A nested loop draws a triangle"
public class Main {
    public static void main(String[] args) {
        for (int row = 1; row <= 4; row++) {
            for (int star = 1; star <= row; star++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
```

Expected output:

```text
*
**
***
****
```

The inner condition is `star <= row`. So row 1 prints one star, row 2 prints two, and so on.

## while Loop

### Definition and Structure

A `while` loop repeats as long as its condition stays true.

```text
while (condition) {
    // loop body
}
```

Unlike `for`, the start and update are not part of the loop header. You write them yourself: the start before the loop and the update inside the body.

### Control Flow

1. Java checks the condition.
2. If it is true, the body runs, then Java returns to step 1.
3. If it is false, the loop ends.

`while` is best when you do not know in advance how many iterations you need.

```java runnable title="A while loop runs until the savings reach the goal"
public class Main {
    public static void main(String[] args) {
        int savings = 0;
        int goal = 5000;
        int months = 0;

        while (savings < goal) {
            savings += 1200;
            months++;
        }

        System.out.println("Months needed: " + months);
        System.out.println("Final savings: " + savings);
    }
}
```

Expected output:

```text
Months needed: 5
Final savings: 6000
```

The program does not know the number of months in advance. It keeps adding money until `savings < goal` becomes false.

After 4 months, savings are `4800`, which is still below `5000`. After month 5, they reach `6000`, and the loop stops.

### Digits of a Number

Here is another case where the count is unknown: counting the digits of a number.

```java runnable title="Count digits by dividing by 10 until nothing is left"
public class Main {
    public static void main(String[] args) {
        int number = 470385;
        int digits = 0;

        while (number > 0) {
            number = number / 10;
            digits++;
        }

        System.out.println("Digits: " + digits);
    }
}
```

Expected output:

```text
Digits: 6
```

Each division by 10 removes the last digit. `470385` becomes `47038`, then `4703`, and so on until it becomes `0`. The loop counts how many steps that takes.

### Nested while Loop

You can nest `while` loops too. Just reset the inner counter before each run of the inner loop.

```java runnable title="Nested while loops print seat labels"
public class Main {
    public static void main(String[] args) {
        char row = 'A';

        while (row <= 'C') {
            int seat = 1;
            while (seat <= 3) {
                System.out.print(row + "" + seat + " ");
                seat++;
            }
            System.out.println();
            row++;
        }
    }
}
```

Expected output:

```text
A1 A2 A3
B1 B2 B3
C1 C2 C3
```

`int seat = 1;` sits inside the outer loop. That means every new row starts again from seat 1.

If you moved it above the outer loop, `seat` would stay at `4` after the first row. The inner loop would not run again, and you would only see row A.

`row + "" + seat` inserts an empty string between the `char` and the `int`, so Java joins them as text.

## do-while Loop

### Definition and Structure

A `do-while` loop runs the body first, then checks the condition.

```text
do {
    // loop body
} while (condition);
```

Notice the semicolon after `while (condition)`. It is required here.

### Control Flow

1. The body runs.
2. Java checks the condition.
3. If it is true, Java returns to step 1.
4. If it is false, the loop ends.

### Guaranteed First Execution

Because the check happens at the end, the body always runs at least once, even when the condition starts as false.

This is useful for a menu. You must show the menu once before you can ask whether to show it again.

```java runnable title="do-while shows the menu before it checks anything"
public class Main {
    public static void main(String[] args) {
        int choice = 0;
        int round = 1;

        do {
            System.out.println("Round " + round + ": 1) Play  2) Quit");
            choice = round == 3 ? 2 : 1;   // pretend the user picks Quit on round 3
            System.out.println("You chose " + choice);
            round++;
        } while (choice != 2);

        System.out.println("Goodbye!");
    }
}
```

Expected output:

```text
Round 1: 1) Play  2) Quit
You chose 1
Round 2: 1) Play  2) Quit
You chose 1
Round 3: 1) Play  2) Quit
You chose 2
Goodbye!
```

The menu appears before the program knows the choice. The loop ends once the choice is `2`.

### How It Differs from while

Here, the same false condition is given to both loops:

```java runnable title="Same false condition: while runs 0 times, do-while runs once"
public class Main {
    public static void main(String[] args) {
        int tickets = 0;

        while (tickets > 0) {
            System.out.println("while: selling a ticket");
        }

        do {
            System.out.println("do-while: selling a ticket");
        } while (tickets > 0);
    }
}
```

Expected output:

```text
do-while: selling a ticket
```

`tickets > 0` is false from the start.

The `while` loop checks first, so its body never runs. The `do-while` loop runs once before it checks, so it prints one line.

| | `while` | `do-while` |
|---|---|---|
| Checks the condition | Before each iteration | After each iteration |
| Type | Entry-controlled | Exit-controlled |
| Minimum number of runs | 0 | 1 |
| Semicolon after `while (...)` | No | Yes |

### Nested do-while Loop

`do-while` loops can be nested too. As with nested `while` loops, reset the inner counter inside the outer loop.

```java runnable title="Nested do-while loops print a small times table"
public class Main {
    public static void main(String[] args) {
        int i = 1;

        do {
            int j = 1;
            do {
                System.out.print(i + "x" + j + "=" + (i * j) + "  ");
                j++;
            } while (j <= 3);
            System.out.println();
            i++;
        } while (i <= 2);
    }
}
```

Expected output:

```text
1x1=1  1x2=2  1x3=3
2x1=2  2x2=4  2x3=6
```

The outer loop runs twice. Each time, the inner loop runs three times.

## Loop Control Statements

Sometimes you need to change a loop's normal path from inside the body. Java gives you two statements for this.

### break Statement

`break` ends the loop immediately. Java jumps to the first line after the loop.

```java runnable title="break stops the search as soon as the item is found"
public class Main {
    public static void main(String[] args) {
        int[] rollNumbers = {104, 117, 121, 135, 142};
        int target = 121;

        for (int i = 0; i < rollNumbers.length; i++) {
            System.out.println("Checking " + rollNumbers[i]);
            if (rollNumbers[i] == target) {
                System.out.println("Found " + target + " at position " + i);
                break;
            }
        }
    }
}
```

Expected output:

```text
Checking 104
Checking 117
Checking 121
Found 121 at position 2
```

Once `121` is found, there is no reason to check `135` and `142`. `break` ends the loop right away.

### continue Statement

`continue` skips the rest of the current iteration. The loop then moves on to the next one.

```java runnable title="continue skips the odd numbers"
public class Main {
    public static void main(String[] args) {
        for (int n = 1; n <= 10; n++) {
            if (n % 2 != 0) {
                continue;
            }
            System.out.print(n + " ");
        }
        System.out.println();
    }
}
```

Expected output:

```text
2 4 6 8 10
```

For an odd number, `continue` jumps straight to `n++`. The `print` line is skipped for that iteration only.

Think of a teacher calling out names. `continue` skips one absent student and moves to the next. `break` stops the roll call completely.

### When to Use break

Use `break` when the rest of the loop is no longer needed:

- you found what you were searching for;
- the user typed "quit";
- an error means continuing makes no sense.

### When to Use continue

Use `continue` when one item should be ignored, but the loop should keep going:

- skipping blank lines in a file;
- skipping cancelled orders when adding up sales;
- skipping invalid values in a list.

In a nested loop, `break` and `continue` only affect the innermost loop they are inside.

## Infinite Loops

An **infinite loop** is a loop whose condition never becomes false. It runs forever, and the program never moves on.

Most infinite loops are mistakes. The usual cause is forgetting to update the counter:

```text
int count = 1;
while (count <= 5) {
    System.out.println(count);
    // count++ is missing, so count stays 1 forever
}
```

`count` is always `1`, so `count <= 5` is always true. The loop prints `1` again and again.

Other common causes:

- counting in the wrong direction, like `i--` in a loop that needs `i` to grow;
- using a condition that can never become false, like `i != 10` when `i` increases by 3.

Some infinite loops are written on purpose, with `while (true)`. Servers and games use this style. They always include a `break` or `return` that ends the loop at the right moment.

```java runnable title="while (true) with a break that always ends it"
public class Main {
    public static void main(String[] args) {
        int attempts = 0;

        while (true) {
            attempts++;
            System.out.println("Attempt " + attempts);
            if (attempts == 3) {
                System.out.println("Connected!");
                break;
            }
        }
    }
}
```

Expected output:

```text
Attempt 1
Attempt 2
Attempt 3
Connected!
```

`while (true)` never stops on its own. The `break` inside is the only way out.

If a program seems frozen and prints the same thing over and over, suspect an infinite loop. Check that the loop variable changes on every iteration and moves toward making the condition false.

## Common mistakes

The following mistakes are common when writing loops. Each row shows what you see, why it happens and how to fix it.

| Symptom | Cause | Fix |
|---|---|---|
| `ArrayIndexOutOfBoundsException` | `<=` used with `array.length` | Use `<` |
| The body runs only once | A `;` right after the loop header | Remove the `;` |
| The program never ends | The loop variable is never updated | Update it inside the body |
| A total is always the last value only | The total is declared inside the loop | Declare it before the loop |
| `';' expected` after a `do-while` | The closing `;` is missing | Add `;` after `while (...)` |
| A nested loop only runs its first row | The inner counter is not reset | Set the inner counter inside the outer loop |

## What to Remember

- A loop repeats its body while a condition is true. Each run is called an iteration.
- `for` and `while` check before each run (entry-controlled). `do-while` checks after, so it always runs at least once.
- Use `for` when you know the count, `while` when you wait for a condition, and `do-while` when the body must run once first.
- In a nested loop, the inner loop finishes all its iterations for each outer iteration.
- `break` ends the loop. `continue` skips to the next iteration.
- An infinite loop never ends. Always make sure the loop variable moves toward making the condition false.

Next: Methods
