Phase 1 · BeginnerModule 5~32 min read

Loops

Repeat work efficiently with while, do-while, for, and enhanced-for loops — plus break, continue, and labels.

What you'll learn

Computers are brilliant at repetition. Loops let you run a block of code again and again — counting, processing lists, retrying until something succeeds — without copy-pasting. Master loops and you unlock most real programs.

By the end you'll be able to:

  • Choose between while, do-while, for, and enhanced for
  • Understand the three parts of a for loop
  • Nest loops to work with grids and patterns
  • Control loops precisely with break, continue, and labels
  • Avoid infinite loops and off-by-one errors
  • Solve classic problems like summing numbers and FizzBuzz

while & do-while

A while loop repeats as long as its condition stays true. It checks the condition before each pass, so if the condition is false from the start, the body never runs. The golden rule: something inside the loop must eventually make the condition false, or it runs forever.

While.java
int count = 3;

while (count > 0) {
    System.out.println(count);
    count--;              // MUST change, or the loop never ends
}
System.out.println("Liftoff!");

A do-while loop is the same idea, but it checks the condition after the body — so the body always runs at least once. It's perfect for menus and input prompts that should show before you validate.

DoWhile.java
int n = 10;

do {
    System.out.println("Runs at least once, n = " + n);
} while (n < 5);          // false immediately — but body already ran
while vs do-while

while

Checks the condition first. If it's false to begin with, the body runs zero times.

do-while

Runs the body once first, then checks. Guarantees at least one run.

The for loop

When you know how many times to repeat (or you're counting), the for loop is the cleanest choice. It packs three things into one line: set up a counter, test a condition, and update the counter — all visible at a glance.

Anatomy of a for loop
for ( int i = 0; i < 5; i++ ) {

1 · Initialization

Runs once before the loop begins.

2 · Condition

Checked before each pass; loop runs while true.

3 · Update

Runs after each pass through the body.

Initialization runs once; condition is checked each pass; update runs after each pass.
ForSum.java
int sum = 0;

for (int i = 1; i <= 5; i++) {
    sum += i;             // 1 + 2 + 3 + 4 + 5
}

System.out.println("Sum of 1..5 = " + sum);

Off-by-one errors

The most common loop bug is looping one time too many or too few. Ask yourself: should the condition use < or <=? For an array of length n, valid indexes are 0 to n-1, so you loop i < n.

The enhanced for (for-each)

When you just want to visit every element of an array or collection — no index needed — the enhanced for loop is shorter and safer. Read for (int x : numbers) as "for each x in numbers":

ForEach.java
int[] scores = {90, 85, 100, 70};
int total = 0;

for (int score : scores) {   // "for each score in scores"
    total += score;
}

System.out.println("Total: " + total);
System.out.println("Average: " + (total / scores.length));

Tip

Use a classic for when you need the index (or want to modify elements by position), and the enhanced for when you simply need to read each value.

Nested loops

A loop can live inside another loop. For every single pass of the outer loop, the inner loop runs completely. That's exactly what you need for grids, tables, and patterns:

Triangle.java
for (int row = 1; row <= 4; row++) {
    for (int col = 1; col <= row; col++) {
        System.out.print("* ");
    }
    System.out.println();     // new line after each row
}

Note

Nesting multiplies the work: an outer loop of n and an inner loop of n runs the inner body n × n times. Keep an eye on that as your data grows — it matters for performance (Module 35).

break, continue & labels

Sometimes you need to interrupt the normal flow. break stops the loop completely, while continue skips just the current pass and moves on to the next:

break vs continue

break

Exits the loop entirely and jumps to the code after it.

continue

Skips the rest of this pass and jumps to the next iteration.

BreakContinue.java
for (int i = 1; i <= 10; i++) {
    if (i == 4) continue;    // skip only 4
    if (i == 7) break;       // stop the whole loop at 7
    System.out.print(i + " ");
}

Note

With nested loops, a plain break only exits the inner loop. A labeled break (e.g. outer: for (...) { ... break outer; }) can exit the outer loop too — useful, but use it sparingly to keep code readable.

Putting it together: FizzBuzz

FizzBuzz is the most famous beginner exercise, and it combines everything so far — a loop, the modulo operator, and an if-else chain. Print 1 to 15, but replace multiples of 3 with "Fizz", multiples of 5 with "Buzz", and multiples of both with "FizzBuzz":

FizzBuzz.java
for (int i = 1; i <= 15; i++) {
    if (i % 15 == 0)      System.out.println("FizzBuzz");
    else if (i % 3 == 0)  System.out.println("Fizz");
    else if (i % 5 == 0)  System.out.println("Buzz");
    else                  System.out.println(i);
}

Tip

Order matters here: check the % 15 case first. If you tested % 3 before % 15, every multiple of 15 would print "Fizz" and never reach "FizzBuzz".

Recap & quick check

Key takeaways

  • while checks before running; do-while runs once then checks (at least one pass).
  • for packs initialization, condition, and update into one line — ideal for counting.
  • The enhanced for (for-each) visits every element without needing an index.
  • break exits the loop; continue skips to the next iteration.
  • Guard against infinite loops (always change the condition) and off-by-one errors.

Quick check

1. Which loop always runs its body at least once?

2. What does 'continue' do inside a loop?

3. For an array of length n, which condition safely visits every index?

4. In nested loops, how many times does the inner body run if each loop goes 1..n?

5. What causes an infinite loop?

Fantastic — you can now automate repetitive work. Next up: Module 6 — Methods & Program Decomposition, where you'll package code into reusable building blocks.