Loop Statements: Repeat Tasks Efficiently

Introduction

This chapter teaches loops in Java—for, enhanced for, while, and do-while. Loops run a block of code repeatedly without copy-pasting. You will also use break, continue, and return in context (introduced in Keywords).

Prerequisites

What Is a Loop

A loop repeats a block of code while a condition holds or for each item in a sequence.

Metaphor:

  • Workout sets: repeat the same exercise N times
  • Assembly line: apply the same step to each item

Without loops, repeated logic becomes long and error-prone.

1) The for Loop

Use for when you know how many iterations you need (or can compute an end condition).

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

Structure:

java
for (initialization; condition; update) {
    // body
}
  • initialization: runs once at start (often int i = 0)
  • condition: checked before each iteration; loop runs while true
  • update: runs after each iteration (often i++)

Print multiplication table fragment:

java
int n = 3;
for (int i = 1; i <= 10; i++) {
    System.out.println(n + " x " + i + " = " + (n * i));
}

2) Enhanced for Loop (for-each)

Iterates over arrays and collections without index variables (collections in later chapters).

java
String[] fruits = {"apple", "banana", "orange"};
for (String fruit : fruits) {
    System.out.println(fruit);
}

You will use this heavily with Arrays.

3) The while Loop

Use while when repetition depends on a condition that may change inside the loop.

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

Warning

Ensure the loop condition eventually becomes false. Otherwise you get an infinite loop that never stops on its own.

4) The do-while Loop

Runs the body at least once, then checks the condition.

java
int number;
try (java.util.Scanner scanner = new java.util.Scanner(System.in)) {
    do {
        System.out.print("Enter a positive number: ");
        number = scanner.nextInt();
    } while (number <= 0);
    System.out.println("Thanks: " + number);
}

Useful for input validation menus.

5) break, continue, and return

break — exit the loop immediately

java
for (int number = 1; number < 10; number++) {
    if (number == 6) {
        System.out.println("Found 6, stop.");
        break;
    }
    System.out.println(number);
}

continue — skip to next iteration

java
for (int number = 1; number < 8; number++) {
    if (number % 2 == 0) {
        continue;  // skip even numbers
    }
    System.out.println(number);
}

return — exit the entire method (ends loops too)

When return runs inside a method, the method finishes—any loop inside stops with it.

java
public static void demo() {
    for (int i = 0; i < 10; i++) {
        if (i == 3) {
            return;
        }
        System.out.println(i);
    }
}

In switch, break prevents fall-through; in loops, break exits the loop—same keyword, different context (Conditionals).

6) Nested Loops

A loop inside another loop—useful for grids and tables.

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

Complexity grows quickly—keep nesting shallow when learning.

7) Real Mini Example: Password Retry

java
import java.util.Scanner;
 
public class PasswordRetry {
    public static void main(String[] args) {
        String correctPassword = "java123";
        int maxAttempts = 3;
 
        try (Scanner scanner = new Scanner(System.in)) {
            for (int attempt = 1; attempt <= maxAttempts; attempt++) {
                System.out.print("Enter password (attempt " + attempt + "): ");
                String input = scanner.nextLine();
 
                if (correctPassword.equals(input)) {
                    System.out.println("Login successful!");
                    return;
                }
 
                System.out.println("Wrong password.");
            }
 
            System.out.println("Account locked. Try again later.");
        }
    }
}

Common Beginner Mistakes

Mistake 1: Infinite while Loop

java
int i = 0;
while (i < 5) {
    System.out.println(i);
    // forgot i++ → infinite loop
}

Mistake 2: Off-by-One Errors

i < 5 runs 0–4; i <= 5 runs 0–5. Match your intent to the bound.

Mistake 3: Modifying Collection While foreach-ing

Do not add/remove elements from a list while enhanced-for over it—use iterator patterns later. Arrays with for-index are safer for some mutations.

Mistake 4: Semicolon After for Header

java
for (int i = 0; i < 5; i++);  // empty loop body!
    System.out.println(i);     // runs once after loop — surprise

Mini Practice

  1. Print sum of numbers 1 to 100 using for
  2. Print only odd numbers between 1 and 20 using continue
  3. Ask user for numbers until they enter 0, then print total (use while)

What’s Next

Store ordered data in Arrays, then build the Ranking Game.

FAQ

When should I use for vs while?

for when iteration count or index is natural; while when condition-driven (unknown iterations upfront).

What is the difference between while and do-while?

do-while always runs the body at least once before checking the condition.

Can I use break in switch and loops?

Yes. Meaning differs: exit a case path vs exit a loop.

Does enhanced for work with arrays?

Yes. It also works with List and other Iterable types later.

How do I avoid infinite loops during practice?

Always change the variable in the condition (e.g. i++) or ensure input eventually satisfies exit criteria.