LearnContact
Lesson 1360 min read

Loops in Java

Learn how to repeat code efficiently in Java using while, do-while, for, enhanced for loops, nested loops, break, continue, and real-world iteration patterns.

Introduction

In the previous lesson, you learned how conditional statements allow Java programs to make decisions. However, many programming problems require the same operation to be performed repeatedly.

Imagine printing numbers from 1 to 100, processing thousands of customer records, repeatedly asking for valid input, or checking every item in a collection. Writing the same statements again and again would be inefficient and difficult to maintain.

Loops solve this problem by allowing a block of code to execute repeatedly while a condition remains true or for a specified number of iterations.

Simple Loop
for (int number = 1; number <= 5; number++) {

    System.out.println(number);

}
Output
1
2
3
4
5
What You Will Learn
  • What loops are.
  • Why repetition is needed in programming.
  • How loops control repeated execution.
  • The main components of a loop.
  • The difference between entry-controlled and exit-controlled loops.
  • How the while loop works.
  • How the do-while loop works.
  • How the for loop works.
  • How enhanced for loops work.
  • How nested loops work.
  • How break terminates a loop.
  • How continue skips an iteration.
  • How labeled break and continue work.
  • How loop variables and scope work.
  • What off-by-one errors are.
  • How infinite loops occur.
  • How counter-controlled loops work.
  • How condition-controlled loops work.
  • How sentinel-controlled loops work.
  • How accumulator patterns work.
  • How to calculate factorials.
  • How to reverse numbers.
  • How to calculate digit sums.
  • How to check palindrome numbers.
  • How to check prime numbers.
  • How to generate Fibonacci numbers.
  • How to build menu-driven programs.
  • Common loop errors.
  • Best practices for writing readable loops.

What are Loops?

A loop is a programming structure that repeatedly executes a block of code until a condition becomes false or another termination condition is reached.

Loop Concept
START

  │
  ▼

CHECK CONDITION

  │
  ├── true ─────► EXECUTE CODE
  │                    │
  │                    ▼
  │                 UPDATE
  │                    │
  │                    └──────┐
  │                           │
  └── false ─────► EXIT LOOP ◄┘
                        │
                        ▼
                     CONTINUE

Why Loops are Needed

Repetition

Execute the same operation multiple times without duplicating code.

Data Processing

Process arrays, collections, records, files, and other groups of data.

Input Validation

Keep asking the user until valid input is provided.

Games

Continuously update game state until the player exits or the game ends.

Calculations

Calculate totals, averages, factorials, sequences, and repeated mathematical operations.

Automation

Repeat tasks efficiently without writing duplicate statements.

Real-World Analogy

Imagine climbing a staircase with ten steps. You repeat the same action until you reach the final step.

Staircase Analogy
CURRENT STEP = 1

        │
        ▼

HAVE WE REACHED STEP 10?

      /       \
    NO         YES
     │           │
     ▼           ▼

CLIMB ONE      STOP
STEP

     │
     ▼

INCREASE CURRENT STEP

     │
     └──────────────► CHECK AGAIN

How Loops Work

General Loop Process
1. INITIALIZE

       │
       ▼

2. CHECK CONDITION

       │
       ├── false ──► EXIT
       │
       └── true
             │
             ▼

3. EXECUTE LOOP BODY

       │
       ▼

4. UPDATE LOOP STATE

       │
       └────────────► RETURN TO CONDITION

Loop Components

Loop Components
// 1. Initialization
int number = 1;

// 2. Condition
while (number <= 5) {

    // 3. Loop body
    System.out.println(number);

    // 4. Update
    number++;

}
Components
INITIALIZATION

Creates starting state


CONDITION

Decides whether loop continues


BODY

Contains repeated statements


UPDATE

Changes loop state

Types of Loops

Java Loop Types
JAVA LOOPS

├── while
│
├── do-while
│
├── for
│
├── Enhanced for
│
└── Nested Loops

Entry-Controlled Loops

An entry-controlled loop checks its condition before executing the loop body.

Entry-Controlled
CHECK CONDITION FIRST

        │
        ▼

      true?
      /   \
    YES    NO
     │      │
     ▼      ▼

EXECUTE   EXIT
BODY
Entry-Controlled Loops in Java
  • while is entry-controlled.
  • for is entry-controlled.
  • The loop body may execute zero times.
  • If the initial condition is false, the body is skipped.

Exit-Controlled Loops

An exit-controlled loop executes its body before checking the condition.

Exit-Controlled
EXECUTE BODY FIRST

        │
        ▼

CHECK CONDITION

      /   \
   true   false
     │      │
     ▼      ▼

REPEAT    EXIT
Exit-Controlled Loop in Java
  • do-while is exit-controlled.
  • Its body executes before the condition is checked.
  • The body always executes at least once.

while Loop

The while loop repeatedly executes a block of code while its condition remains true.

while Loop Syntax

Syntax
while (condition) {

    // Statements

}

How while Works

while Flow
START

  │
  ▼

CONDITION?

  ├── false ─────► EXIT
  │
  └── true
        │
        ▼

   EXECUTE BODY

        │
        ▼

      UPDATE

        │
        └────────► CONDITION

Basic while Example

Print 1 to 5
int number = 1;

while (number <= 5) {

    System.out.println(number);

    number++;

}
Output
1
2
3
4
5

Counting Forward

Count 1 to 10
int count = 1;

while (count <= 10) {

    System.out.println(count);

    count++;

}

Counting Backward

Countdown
int count = 10;

while (count >= 1) {

    System.out.println(count);

    count--;

}

System.out.println("Go!");

while with User Input

Repeat until Correct Number
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner =
                new Scanner(System.in);

        int number = 0;

        while (number != 10) {

            System.out.print(
                    "Enter 10: "
            );

            number =
                    scanner.nextInt();

        }

        System.out.println(
                "Correct!"
        );

    }
}

Sentinel-Controlled Loop

A sentinel value is a special value used to indicate that input or processing should stop.

Stop with -1
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner =
                new Scanner(System.in);

        int number = 0;

        while (number != -1) {

            System.out.print(
                    "Enter a number (-1 to stop): "
            );

            number =
                    scanner.nextInt();

        }

        System.out.println(
                "Program stopped."
        );

    }
}

Sum using while

Sum 1 to 100
int number = 1;
int sum = 0;

while (number <= 100) {

    sum += number;

    number++;

}

System.out.println(
        "Sum: " + sum
);

Infinite while Loop

Infinite Loop
while (true) {

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

}
Infinite Loops
  • An infinite loop never reaches a false condition.
  • It may be intentional in servers, games, and event loops.
  • Unintentional infinite loops usually happen because the loop state is never updated.
  • Always verify how a loop will terminate.

do-while Loop

The do-while loop executes its body first and checks the condition afterward. Therefore, its body always executes at least once.

do-while Syntax

Syntax
do {

    // Statements

} while (condition);

How do-while Works

do-while Flow
START

  │
  ▼

EXECUTE BODY

  │
  ▼

UPDATE

  │
  ▼

CONDITION?

  ├── true ─────► EXECUTE BODY AGAIN
  │
  └── false ────► EXIT

Basic do-while Example

Print 1 to 5
int number = 1;

do {

    System.out.println(number);

    number++;

} while (number <= 5);

while vs do-while

Comparison
while

Condition checked first
May execute zero times
Entry-controlled


do-while

Body executed first
Executes at least once
Exit-controlled
Difference Example
int number = 10;

while (number < 5) {

    System.out.println(
            "while executed"
    );

}

do {

    System.out.println(
            "do-while executed"
    );

} while (number < 5);
Output
do-while executed

Menu using do-while

Menu Program
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner =
                new Scanner(System.in);

        int choice;

        do {

            System.out.println(
                    "1. Add"
            );

            System.out.println(
                    "2. Edit"
            );

            System.out.println(
                    "3. Delete"
            );

            System.out.println(
                    "4. Exit"
            );

            System.out.print(
                    "Enter choice: "
            );

            choice =
                    scanner.nextInt();

            switch (choice) {

                case 1 ->
                    System.out.println(
                            "Add selected"
                    );

                case 2 ->
                    System.out.println(
                            "Edit selected"
                    );

                case 3 ->
                    System.out.println(
                            "Delete selected"
                    );

                case 4 ->
                    System.out.println(
                            "Goodbye!"
                    );

                default ->
                    System.out.println(
                            "Invalid choice"
                    );

            }

        } while (choice != 4);

    }
}

Input Validation

Validate Age
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner =
                new Scanner(System.in);

        int age;

        do {

            System.out.print(
                    "Enter age (0-120): "
            );

            age =
                    scanner.nextInt();

        } while (
            age < 0 || age > 120
        );

        System.out.println(
                "Valid age: " + age
        );

    }
}

for Loop

The for loop is commonly used when the number of iterations is known or controlled by a counter.

for Loop Syntax

Syntax
for (
    initialization;
    condition;
    update
) {

    // Statements

}

How for Works

for Flow
INITIALIZATION

      │
      ▼

CONDITION?

 ├── false ─────► EXIT
 │
 └── true
       │
       ▼

  EXECUTE BODY

       │
       ▼

     UPDATE

       │
       └────────► CONDITION

for Loop Execution Order

Execution Order
1. INITIALIZATION

Runs once


2. CONDITION

Checked before every iteration


3. BODY

Runs when condition is true


4. UPDATE

Runs after the body


5. RETURN TO CONDITION

Basic for Example

Print 1 to 5
for (
    int number = 1;
    number <= 5;
    number++
) {

    System.out.println(number);

}

Counting Backward with for

Countdown
for (
    int number = 10;
    number >= 1;
    number--
) {

    System.out.println(number);

}

System.out.println("Go!");

Custom Increment

Even Numbers
for (
    int number = 2;
    number <= 20;
    number += 2
) {

    System.out.println(number);

}

Multiple Variables in for

Two Counters
for (
    int left = 1, right = 10;
    left <= right;
    left++, right--
) {

    System.out.println(
        left + " - " + right
    );

}

Omitting for Components

Initialization Outside
int number = 1;

for (
    ;
    number <= 5;
    number++
) {

    System.out.println(number);

}
Update inside Body
for (
    int number = 1;
    number <= 5;
) {

    System.out.println(number);

    number++;

}

Infinite for Loop

Infinite for
for (;;) {

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

}

while vs for

Comparison
USE for WHEN:

Iteration count is known
Counter controls repetition
Initialization and update belong together


USE while WHEN:

Iteration count is unknown
Loop depends on a changing condition
Loop depends on user input
Loop depends on external state

Enhanced for Loop

The enhanced for loop, also called the for-each loop, is designed to process each element of an array or iterable collection.

Enhanced for Syntax

Syntax
for (
    dataType element : collection
) {

    // Use element

}

Enhanced for with Arrays

Process Array
int[] numbers = {
    10, 20, 30, 40, 50
};

for (int number : numbers) {

    System.out.println(number);

}

Traditional vs Enhanced for

Traditional for
int[] numbers = {
    10, 20, 30
};

for (
    int index = 0;
    index < numbers.length;
    index++
) {

    System.out.println(
            numbers[index]
    );

}
Enhanced for
for (int number : numbers) {

    System.out.println(number);

}

Limitations of Enhanced for

Enhanced for Limitations
  • It does not directly provide the current index.
  • It always processes elements in the iteration order.
  • It is not suitable when you need custom index movement.
  • Assigning a new value to the loop variable does not replace a primitive array element.
  • Use a traditional for loop when index control is required.

Nested Loops

A nested loop is a loop placed inside another loop. The inner loop completes all its iterations for every iteration of the outer loop.

Nested Loop Syntax

Syntax
for (
    int outer = 1;
    outer <= 3;
    outer++
) {

    for (
        int inner = 1;
        inner <= 3;
        inner++
    ) {

        // Statements

    }

}

How Nested Loops Work

Nested Execution
OUTER ITERATION 1

    INNER 1
    INNER 2
    INNER 3


OUTER ITERATION 2

    INNER 1
    INNER 2
    INNER 3


OUTER ITERATION 3

    INNER 1
    INNER 2
    INNER 3

Multiplication Table

Tables 1 to 5
for (
    int table = 1;
    table <= 5;
    table++
) {

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

        System.out.println(
            table
            + " x "
            + multiplier
            + " = "
            + (table * multiplier)
        );

    }

    System.out.println();

}

Pattern Printing

Nested loops are commonly used for pattern printing. The outer loop usually controls rows, while the inner loop controls columns or values inside each row.

Rectangle Pattern

Rectangle
for (
    int row = 1;
    row <= 4;
    row++
) {

    for (
        int column = 1;
        column <= 6;
        column++
    ) {

        System.out.print("* ");

    }

    System.out.println();

}
Output
* * * * * *
* * * * * *
* * * * * *
* * * * * *

Right Triangle Pattern

Triangle
for (
    int row = 1;
    row <= 5;
    row++
) {

    for (
        int column = 1;
        column <= row;
        column++
    ) {

        System.out.print("* ");

    }

    System.out.println();

}
Output
*
* *
* * *
* * * *
* * * * *

Number Pattern

Number Triangle
for (
    int row = 1;
    row <= 5;
    row++
) {

    for (
        int number = 1;
        number <= row;
        number++
    ) {

        System.out.print(
                number + " "
        );

    }

    System.out.println();

}
Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Loop Control Statements

Loop Control
LOOP CONTROL

├── break
│   └── Terminate loop
│
├── continue
│   └── Skip current iteration
│
├── Labeled break
│   └── Exit named outer structure
│
└── Labeled continue
    └── Continue named outer loop

break Statement

The break statement immediately terminates the nearest loop or switch statement.

break Example

Stop at 5
for (
    int number = 1;
    number <= 10;
    number++
) {

    if (number == 5) {

        break;

    }

    System.out.println(number);

}
Output
1
2
3
4

Searching with break

Find Target
int[] numbers = {
    10, 25, 40, 55, 70
};

int target = 40;
boolean found = false;

for (int number : numbers) {

    if (number == target) {

        found = true;

        break;

    }

}

System.out.println(
        found
        ? "Target found"
        : "Target not found"
);

continue Statement

The continue statement skips the remaining statements in the current iteration and moves to the next iteration.

continue Example

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

    if (number == 5) {

        continue;

    }

    System.out.println(number);

}

Skip Even Numbers

Print Odd Numbers
for (
    int number = 1;
    number <= 20;
    number++
) {

    if (number % 2 == 0) {

        continue;

    }

    System.out.println(number);

}

break vs continue

Comparison
break

Terminates entire loop
Execution continues after loop


continue

Skips current iteration
Loop continues with next iteration

Labeled break

Exit Outer Loop
outerLoop:

for (
    int row = 1;
    row <= 3;
    row++
) {

    for (
        int column = 1;
        column <= 3;
        column++
    ) {

        if (
            row == 2
            && column == 2
        ) {

            break outerLoop;

        }

        System.out.println(
            row + ", " + column
        );

    }

}

Labeled continue

Continue Outer Loop
outerLoop:

for (
    int row = 1;
    row <= 3;
    row++
) {

    for (
        int column = 1;
        column <= 3;
        column++
    ) {

        if (column == 2) {

            continue outerLoop;

        }

        System.out.println(
            row + ", " + column
        );

    }

}
Use Labels Carefully
  • Labels can control outer loops directly.
  • They can be useful in deeply nested searching logic.
  • Excessive label usage can make code difficult to follow.
  • Consider extracting complex nested logic into methods.

Loop Variables and Scope

Loop Variable Scope
for (
    int number = 1;
    number <= 5;
    number++
) {

    System.out.println(number);

}

// Invalid:
// System.out.println(number);

A variable declared inside the for initialization belongs to the loop scope and cannot be accessed after the loop ends.

Off-by-One Errors

An off-by-one error occurs when a loop executes one time too many or one time too few.

Five Iterations
for (
    int number = 1;
    number <= 5;
    number++
) {

    System.out.println(number);

}
Only Four Iterations
for (
    int number = 1;
    number < 5;
    number++
) {

    System.out.println(number);

}
Check Loop Boundaries
  • Understand the starting value.
  • Understand whether the final value should be included.
  • Check whether < or <= is correct.
  • Test the first and last iterations.

Infinite Loops

Missing Update
int number = 1;

while (number <= 5) {

    System.out.println(number);

    // number never changes

}
Wrong Update Direction
int number = 1;

while (number <= 5) {

    System.out.println(number);

    number--;

}

Counter-Controlled Loops

Fixed Repetition
for (
    int count = 1;
    count <= 10;
    count++
) {

    System.out.println(
            "Iteration " + count
    );

}

Condition-Controlled Loops

Repeat while Balance Exists
double balance = 1000;

while (balance > 0) {

    balance -= 100;

    System.out.println(
            "Balance: " + balance
    );

}

Sentinel-Controlled Loops

Read until -1
Scanner scanner =
        new Scanner(System.in);

int value;

while (true) {

    System.out.print(
            "Enter value (-1 to stop): "
    );

    value =
            scanner.nextInt();

    if (value == -1) {

        break;

    }

    System.out.println(
            "You entered: " + value
    );

}

Accumulator Pattern

An accumulator stores a running result that is updated during each loop iteration.

Accumulator
int total = 0;

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

    total += number;

}

System.out.println(total);

Running Total

Sum User Values
int[] values = {
    10, 20, 30, 40
};

int total = 0;

for (int value : values) {

    total += value;

}

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

Product Accumulator

Multiply Values
int product = 1;

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

    product *= number;

}

System.out.println(product);

Finding Maximum

Maximum Value
int[] numbers = {
    45, 12, 89, 34, 67
};

int maximum = numbers[0];

for (int number : numbers) {

    if (number > maximum) {

        maximum = number;

    }

}

System.out.println(
        "Maximum: " + maximum
);

Finding Minimum

Minimum Value
int[] numbers = {
    45, 12, 89, 34, 67
};

int minimum = numbers[0];

for (int number : numbers) {

    if (number < minimum) {

        minimum = number;

    }

}

System.out.println(
        "Minimum: " + minimum
);

Counting Matches

Count Even Numbers
int[] numbers = {
    10, 15, 20, 25, 30
};

int count = 0;

for (int number : numbers) {

    if (number % 2 == 0) {

        count++;

    }

}

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

Factorial Program

Calculate Factorial
int number = 5;
long factorial = 1;

for (
    int value = 1;
    value <= number;
    value++
) {

    factorial *= value;

}

System.out.println(
    number
    + "! = "
    + factorial
);
Output
5! = 120

Multiplication Table Program

Table of 7
int number = 7;

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

    System.out.println(
        number
        + " x "
        + multiplier
        + " = "
        + (number * multiplier)
    );

}

Reverse a Number

Reverse Digits
int number = 12345;
int reversed = 0;

while (number != 0) {

    int digit =
            number % 10;

    reversed =
            reversed * 10 + digit;

    number /= 10;

}

System.out.println(
        "Reversed: " + reversed
);

Sum of Digits

Digit Sum
int number = 5832;
int sum = 0;

while (number != 0) {

    int digit =
            number % 10;

    sum += digit;

    number /= 10;

}

System.out.println(
        "Sum: " + sum
);

Count Digits

Digit Count
int number = 987654;
int count = 0;

while (number != 0) {

    number /= 10;

    count++;

}

System.out.println(
        "Digits: " + count
);
Special Case for Zero
  • The number 0 contains one digit.
  • A loop using while (number != 0) executes zero times for zero.
  • Handle zero separately when counting digits.

Palindrome Number

Palindrome Check
int number = 12321;
int original = number;
int reversed = 0;

while (number != 0) {

    int digit =
            number % 10;

    reversed =
            reversed * 10 + digit;

    number /= 10;

}

if (original == reversed) {

    System.out.println(
            "Palindrome"
    );

} else {

    System.out.println(
            "Not a palindrome"
    );

}

Prime Number Check

Prime Check
int number = 29;
boolean prime = number > 1;

for (
    int divisor = 2;
    divisor * divisor <= number;
    divisor++
) {

    if (number % divisor == 0) {

        prime = false;

        break;

    }

}

System.out.println(
    prime
    ? "Prime number"
    : "Not a prime number"
);

Fibonacci Series

First 10 Fibonacci Numbers
int first = 0;
int second = 1;

for (
    int count = 1;
    count <= 10;
    count++
) {

    System.out.print(
            first + " "
    );

    int next =
            first + second;

    first = second;

    second = next;

}
Output
0 1 1 2 3 5 8 13 21 34

GCD Program

Euclidean Algorithm
int first = 48;
int second = 18;

while (second != 0) {

    int remainder =
            first % second;

    first = second;

    second = remainder;

}

System.out.println(
        "GCD: " + first
);

Guessing Game

Number Guessing Game
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner =
                new Scanner(System.in);

        int secretNumber = 7;
        int guess;
        int attempts = 0;

        do {

            System.out.print(
                    "Guess the number: "
            );

            guess =
                    scanner.nextInt();

            attempts++;

            if (guess < secretNumber) {

                System.out.println(
                        "Too low"
                );

            } else if (
                guess > secretNumber
            ) {

                System.out.println(
                        "Too high"
                );

            }

        } while (
            guess != secretNumber
        );

        System.out.println(
            "Correct in "
            + attempts
            + " attempts!"
        );

    }
}
Calculator
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner =
                new Scanner(System.in);

        int choice;

        do {

            System.out.println(
                    "1. Add"
            );

            System.out.println(
                    "2. Subtract"
            );

            System.out.println(
                    "3. Multiply"
            );

            System.out.println(
                    "4. Divide"
            );

            System.out.println(
                    "5. Exit"
            );

            System.out.print(
                    "Enter choice: "
            );

            choice =
                    scanner.nextInt();

            if (choice >= 1 && choice <= 4) {

                System.out.print(
                        "Enter first number: "
                );

                double first =
                        scanner.nextDouble();

                System.out.print(
                        "Enter second number: "
                );

                double second =
                        scanner.nextDouble();

                switch (choice) {

                    case 1 ->
                        System.out.println(
                                first + second
                        );

                    case 2 ->
                        System.out.println(
                                first - second
                        );

                    case 3 ->
                        System.out.println(
                                first * second
                        );

                    case 4 -> {

                        if (second != 0) {

                            System.out.println(
                                    first / second
                            );

                        } else {

                            System.out.println(
                                    "Cannot divide by zero"
                            );

                        }

                    }

                }

            } else if (choice != 5) {

                System.out.println(
                        "Invalid choice"
                );

            }

        } while (choice != 5);

        System.out.println(
                "Calculator closed."
        );

    }
}

Common Loop Errors

Common Errors
LOOP ERRORS

├── Missing Update
├── Wrong Update Direction
├── Incorrect Condition
├── Off-by-One Error
├── Accidental Infinite Loop
├── Semicolon after Loop Header
├── Updating Wrong Variable
├── Resetting Accumulator inside Loop
├── Incorrect Initial Value
├── Incorrect Boundary Operator
├── Modifying Loop Counter Unexpectedly
├── Forgetting break
├── Misusing continue
├── Infinite Input Loop
├── Incorrect Sentinel Handling
├── Array Index Out of Bounds
├── Excessive Nested Loops
├── Confusing while with do-while
├── Expecting do-while to Skip First Execution
├── Expecting Enhanced for to Provide Index
├── Modifying Primitive Array through for-each Variable
├── Using break When continue is Needed
├── Using continue When break is Needed
└── Failing to Test Boundary Iterations
Accidental Semicolon
for (
    int number = 1;
    number <= 5;
    number++
);

{
    System.out.println(
            "This is not the loop body"
    );
}

Best Practices

  • Choose the loop type that best matches the problem.
  • Use for when the number of iterations is known.
  • Use while when repetition depends on a condition.
  • Use do-while when the body must execute at least once.
  • Use enhanced for when processing every element without needing an index.
  • Use meaningful loop variable names.
  • Use index for array positions.
  • Use count for counting iterations.
  • Use row and column for grid-based loops.
  • Initialize loop variables correctly.
  • Write clear termination conditions.
  • Ensure the loop state changes toward termination.
  • Verify update direction.
  • Check whether ++ or -- is required.
  • Use += for larger increments.
  • Use -= for larger decrements.
  • Avoid changing the loop counter unexpectedly inside the body.
  • Use braces consistently.
  • Indent nested loops clearly.
  • Keep loop bodies focused.
  • Avoid very large loop bodies.
  • Extract complex repeated logic into methods.
  • Avoid unnecessary nested loops.
  • Consider performance when loops process large datasets.
  • Use break when the required result has been found.
  • Use continue when only the current iteration should be skipped.
  • Do not overuse break and continue.
  • Use labels only when they genuinely simplify nested control flow.
  • Avoid complex labeled control flow.
  • Use boolean flags when they make termination clearer.
  • Use sentinel values that cannot be confused with valid input.
  • Document unusual sentinel values.
  • Validate user input.
  • Handle invalid input without creating infinite loops.
  • Test zero iterations.
  • Test exactly one iteration.
  • Test multiple iterations.
  • Test the first boundary.
  • Test the last boundary.
  • Test values just outside boundaries.
  • Watch for off-by-one errors.
  • Use < when the upper boundary is excluded.
  • Use <= when the upper boundary is included.
  • Remember that array indexes start at zero.
  • Use index < array.length when traversing arrays.
  • Never use index <= array.length for normal array traversal.
  • Initialize sum accumulators to zero.
  • Initialize product accumulators to one.
  • Initialize maximum and minimum values carefully.
  • Use the first actual element when possible for maximum and minimum.
  • Do not reset accumulators inside the loop accidentally.
  • Preserve original values when a loop modifies a number.
  • Handle zero separately in digit-processing algorithms when necessary.
  • Consider negative numbers in numeric algorithms.
  • Use long when factorial values may exceed int range.
  • Understand that even long factorials overflow eventually.
  • Use efficient conditions for prime checking.
  • Stop searching once a result is found.
  • Avoid repeated calculations inside loop conditions when unnecessary.
  • Prefer readable code over clever compact loops.
  • Use blank lines to separate major loop steps.
  • Comment why a complex loop exists.
  • Do not comment obvious increments unnecessarily.
  • Use enhanced for loops for read-only element processing.
  • Use traditional for loops when indexes are required.
  • Use while true with break only when it makes the termination logic clearer.
  • Always make intentional infinite loops obvious.
  • Avoid accidental infinite loops.
  • Review every loop for a guaranteed termination path.
  • Test loops with realistic data sizes.
  • Consider algorithm complexity for nested loops.
  • Remember that two nested loops can significantly increase work.
  • Use appropriate data structures to avoid unnecessary looping.
  • Keep user interface logic separate from complex processing when applications grow.
  • Write loops that are easy to understand and maintain.

Loop Selection Guide

Which Loop Should You Use?
KNOWN NUMBER OF ITERATIONS?

        │
        ├── YES ─────► for
        │
        └── NO
             │
             ▼

MUST BODY EXECUTE AT LEAST ONCE?

        │
        ├── YES ─────► do-while
        │
        └── NO ──────► while


PROCESS EVERY ARRAY OR COLLECTION ELEMENT?

        │
        ├── NEED INDEX ─────► for
        │
        └── NO INDEX NEEDED ─► enhanced for

Loop Checklist

Checklist
LOOP CHECKLIST

[ ] Correct loop type selected

[ ] Initialization is correct

[ ] Condition is correct

[ ] Update is correct

[ ] Update moves toward termination

[ ] Loop can terminate

[ ] First iteration tested

[ ] Last iteration tested

[ ] Zero iterations considered

[ ] One iteration considered

[ ] Boundary values tested

[ ] < and <= checked carefully

[ ] No accidental semicolon

[ ] Counter not modified unexpectedly

[ ] Accumulator initialized correctly

[ ] Accumulator not reset inside loop

[ ] Sentinel value is clear

[ ] Invalid input is handled

[ ] break is used correctly

[ ] continue is used correctly

[ ] Nested loops are necessary

[ ] Labels are genuinely useful

[ ] Array boundaries are safe

[ ] Enhanced for is suitable

[ ] Original values preserved when needed

[ ] Zero handled in digit algorithms

[ ] Negative values considered

[ ] Infinite loop is intentional

[ ] Loop body remains readable

[ ] Performance is acceptable

[ ] Every termination path is understood

Common Misconceptions

Avoid These Misconceptions
  • A loop does not automatically terminate unless its condition eventually becomes false or control exits it.
  • A while loop may execute zero times.
  • A for loop may execute zero times.
  • A do-while loop always executes at least once.
  • The semicolon after a do-while condition is required.
  • A semicolon after a while or for header usually creates an empty loop body.
  • The update expression in a for loop runs after the body.
  • The initialization section of a for loop runs only once.
  • Multiple variables can be initialized in one for loop when they share a compatible declaration structure.
  • A for loop does not have to increment by one.
  • A for loop can count backward.
  • A for loop can omit initialization, condition, or update sections.
  • for (;;) creates an infinite loop.
  • break terminates the loop.
  • continue does not terminate the loop.
  • continue skips only the remaining work in the current iteration.
  • A break inside a nested loop normally exits only the nearest loop.
  • Labels can target outer loops.
  • Enhanced for loops do not directly expose indexes.
  • Changing a primitive enhanced-for variable does not modify the original array element.
  • Nested loops multiply the amount of repeated work.
  • Off-by-one errors are boundary errors.
  • An accumulator for addition normally starts at zero.
  • An accumulator for multiplication normally starts at one.
  • The original number may need to be saved before digit-processing loops modify it.
  • Zero requires special handling in some digit-counting algorithms.
  • A prime number must be greater than one.
  • Loops are not always the best solution for every repeated-looking problem.
  • Shorter loop code is not automatically clearer.
  • Infinite loops can be intentional.
  • Every loop should have an understood termination strategy.

Practice Exercises

Exercise 1: Print Numbers
  • Print numbers from 1 to 100.
  • Solve using while.
  • Solve using do-while.
  • Solve using for.
Exercise 2: Even Numbers
  • Print all even numbers from 1 to 100.
  • Create one solution using a condition.
  • Create another solution using an increment of 2.
Exercise 3: Multiplication Table
  • Read a number from the user.
  • Print its multiplication table from 1 to 10.
  • Use a for loop.
Exercise 4: Sum of Natural Numbers
  • Read a positive number n.
  • Calculate the sum from 1 to n.
  • Use an accumulator.
  • Reject negative input.
Exercise 5: Factorial
  • Read a non-negative integer.
  • Calculate its factorial.
  • Remember that 0! equals 1.
  • Use long for the result.
Exercise 6: Reverse Number
  • Read an integer.
  • Reverse its digits.
  • Display the reversed number.
Exercise 7: Palindrome Number
  • Read a number.
  • Preserve the original value.
  • Reverse the number.
  • Compare the original and reversed values.
Exercise 8: Prime Number
  • Read an integer.
  • Check whether it is greater than one.
  • Search for a divisor.
  • Stop early when a divisor is found.
Exercise 9: Fibonacci Series
  • Read the number of terms.
  • Generate the Fibonacci sequence.
  • Handle zero or negative term counts.
Exercise 10: Pattern Printing
  • Print a rectangle.
  • Print a right triangle.
  • Print an inverted triangle.
  • Print a number triangle.
  • Use nested loops.

Common Interview Questions

What is a loop?

A loop repeatedly executes a block of code while a condition remains true or until another termination condition is reached.

What loop types are available in Java?

Java provides while, do-while, for, and enhanced for loops.

What is the difference between while and do-while?

while checks the condition before the body, while do-while checks it after the body and therefore executes at least once.

When should a for loop be used?

A for loop is commonly used when repetition is controlled by a counter or the number of iterations is known.

What is an enhanced for loop?

It is a loop designed to process each element of an array or iterable collection without manually managing an index.

What is an infinite loop?

An infinite loop is a loop whose termination condition never becomes false or is never reached.

What does break do?

break immediately terminates the nearest loop or switch statement.

What does continue do?

continue skips the remaining statements in the current iteration and proceeds to the next iteration.

What is an off-by-one error?

It is an error where a loop executes one iteration too many or one iteration too few.

What is a nested loop?

A nested loop is a loop placed inside another loop.

What is a sentinel value?

A sentinel is a special value used to signal that repeated input or processing should stop.

What is an accumulator?

An accumulator stores a running result that is updated during loop iterations.

Can a for loop have multiple variables?

Yes. Multiple variables can be initialized and updated in a for loop.

Can parts of a for loop be omitted?

Yes. Initialization, condition, and update sections may be omitted, although the semicolons remain required.

What does for (;;) mean?

It creates an infinite for loop.

Frequently Asked Questions

Which loop should beginners use first?

Learn all loop types. Use for for known repetition counts, while for condition-based repetition, and do-while when the body must run at least once.

Can a while loop execute zero times?

Yes. If its initial condition is false, the body is skipped.

Can a do-while loop execute zero times?

No. Its body always executes at least once.

Can I use break inside any loop?

Yes. break can terminate while, do-while, and for loops.

Does continue stop the loop?

No. It skips the rest of the current iteration and continues with the next iteration.

Why is my loop running forever?

The condition may always remain true, the loop variable may not be updated, or the update may move in the wrong direction.

Should I always use enhanced for with arrays?

No. Use it when you only need each value. Use a traditional for loop when you need indexes or custom traversal.

Are nested loops bad?

No, but they increase repeated work. Use them when the problem naturally requires multiple dimensions or combinations.

What should I learn after loops?

The next lesson covers methods in Java.

Key Takeaways

  • Loops repeat blocks of code.
  • Loops reduce code duplication.
  • Every loop needs a clear repetition rule.
  • Initialization establishes the starting state.
  • The condition determines whether repetition continues.
  • The loop body contains repeated work.
  • The update changes loop state.
  • while is an entry-controlled loop.
  • A while loop may execute zero times.
  • do-while is an exit-controlled loop.
  • A do-while loop always executes at least once.
  • The semicolon after a do-while condition is required.
  • for is commonly used for counter-controlled repetition.
  • A for loop combines initialization, condition, and update.
  • Initialization runs once.
  • The condition is checked before each iteration.
  • The update runs after each iteration.
  • A for loop can count forward.
  • A for loop can count backward.
  • A for loop can use custom increments.
  • A for loop can manage multiple variables.
  • for (;;) creates an infinite loop.
  • Enhanced for processes array or collection elements.
  • Enhanced for does not directly provide an index.
  • Traditional for is better when index control is needed.
  • Nested loops place one loop inside another.
  • The inner loop completes for each outer iteration.
  • Nested loops are useful for tables and patterns.
  • break terminates a loop.
  • continue skips the current iteration.
  • Labeled break can exit an outer loop.
  • Labeled continue can continue an outer loop.
  • Labels should be used carefully.
  • Loop variables have scope.
  • Variables declared in a for header usually belong to the loop scope.
  • Off-by-one errors affect loop boundaries.
  • < and <= produce different iteration counts.
  • Infinite loops may be intentional or accidental.
  • Missing updates commonly cause infinite loops.
  • Wrong update direction can cause infinite loops.
  • Counter-controlled loops repeat a known number of times.
  • Condition-controlled loops depend on changing state.
  • Sentinel-controlled loops stop on a special value.
  • Accumulators store running results.
  • Sum accumulators usually start at zero.
  • Product accumulators usually start at one.
  • Loops can find maximum and minimum values.
  • Loops can count matching values.
  • Loops can calculate factorials.
  • Loops can process digits.
  • Loops can reverse numbers.
  • Loops can calculate digit sums.
  • Loops can check palindrome numbers.
  • Loops can test prime numbers.
  • Loops can generate Fibonacci sequences.
  • Loops can build interactive menus.
  • Input validation commonly uses loops.
  • Every loop should have an understood termination path.
  • Boundary testing is essential.
  • Readable loops are easier to maintain.
  • The correct loop depends on the problem.

Summary

Loops allow Java programs to repeat operations efficiently without duplicating code. They are essential for processing data, validating input, performing calculations, building menus, and implementing repeated application behavior.

The while loop checks its condition before execution and is useful when the number of iterations is unknown. The do-while loop checks its condition after execution and therefore always runs at least once.

The for loop is ideal for counter-controlled repetition because initialization, condition, and update are written together. The enhanced for loop provides a simpler way to process every element of an array or iterable collection.

Nested loops allow repeated operations within repeated operations and are commonly used for tables, grids, combinations, and pattern printing.

The break statement terminates a loop immediately, while continue skips the remaining work in the current iteration. Labeled versions can control outer loops but should be used carefully.

Correct initialization, conditions, updates, and boundaries are essential. Missing updates, incorrect operators, wrong update directions, and off-by-one errors are among the most common loop problems.

Loops support important programming patterns including counters, sentinels, accumulators, searching, maximum and minimum calculations, digit processing, factorials, prime checking, and sequence generation.

Choosing the correct loop structure and writing a clear termination condition makes Java programs safer, easier to understand, and easier to maintain.

Lesson 13 Completed
  • You understand what loops are.
  • You understand why repetition is needed.
  • You understand how loops work.
  • You understand loop components.
  • You know the main Java loop types.
  • You understand entry-controlled loops.
  • You understand exit-controlled loops.
  • You can use while loops.
  • You understand while syntax.
  • You can count forward with while.
  • You can count backward with while.
  • You can use while with user input.
  • You understand sentinel-controlled loops.
  • You can calculate sums with while.
  • You understand infinite while loops.
  • You can use do-while loops.
  • You understand do-while syntax.
  • You understand why do-while executes at least once.
  • You can compare while and do-while.
  • You can build menus with do-while.
  • You can validate input with loops.
  • You can use for loops.
  • You understand for syntax.
  • You understand for execution order.
  • You can count forward and backward with for.
  • You can use custom increments.
  • You can use multiple for variables.
  • You understand omitted for components.
  • You understand infinite for loops.
  • You can compare while and for.
  • You can use enhanced for loops.
  • You can process arrays with enhanced for.
  • You can compare traditional and enhanced for loops.
  • You understand enhanced for limitations.
  • You can use nested loops.
  • You understand nested loop execution.
  • You can generate multiplication tables.
  • You can print patterns.
  • You can use break.
  • You can search efficiently with break.
  • You can use continue.
  • You can compare break and continue.
  • You understand labeled break.
  • You understand labeled continue.
  • You understand loop variable scope.
  • You understand off-by-one errors.
  • You can identify infinite loops.
  • You understand counter-controlled loops.
  • You understand condition-controlled loops.
  • You understand sentinel-controlled loops.
  • You understand accumulator patterns.
  • You can calculate running totals.
  • You can calculate products.
  • You can find maximum values.
  • You can find minimum values.
  • You can count matching values.
  • You can calculate factorials.
  • You can generate multiplication tables.
  • You can reverse numbers.
  • You can calculate digit sums.
  • You can count digits.
  • You can check palindrome numbers.
  • You can check prime numbers.
  • You can generate Fibonacci sequences.
  • You can calculate GCD.
  • You can build a guessing game.
  • You can build a menu-driven calculator.
  • You can identify common loop errors.
  • You know loop best practices.
  • You know how to choose the correct loop.
  • You are ready to learn methods.
Next Lesson →

Methods in Java