SyntaxPilot
Courses/Java/Lesson 6

Java · Lesson 6 of 51 · 11 min

Loops: for, while, do-while

queued

These are the notes for Java episode 6. You will learn why copy-pasting code to repeat it breaks, the while loop and the infinite-loop trap, the for loop (start, check and step in one line), off-by-one errors, loop-variable scope, the accumulator pattern, do-while for menus that must show at least once, break and continue, nested loops and star patterns, and the stray-semicolon trap. Every example below runs as-is in the SyntaxPilot compiler, with its real output from javac 21.

The problem: "write it 100 times"

The classic school punishment: write "I will not talk in class" 100 times. With what we knew, one println prints one line, so 100 lines of output need 100 lines of code:

public class Main {
    public static void main(String[] args) {
        System.out.println("1. I will not talk in class");
        System.out.println("2. I will not talk in class");
        System.out.println("3. I will not talk in class");
        System.out.println("4. I will not talk in clas");
        System.out.println("5. I will not talk in class");
        // ... 95 more lines
    }
}
1. I will not talk in class
2. I will not talk in class
3. I will not talk in class
4. I will not talk in clas
5. I will not talk in class

Why it failed: a typo slipped into line 4 while copying, changing the sentence means editing 100 lines, and 1,000 times means pasting 900 more. The code grows with the work. We want to write the work once and say "repeat it".

The while loop

Real-life example: filling a bucket with a mug. Before every mug you check "is it full?"; if not, pour one more and count it.

Filling a bucket In Java
"Is the bucket full yet?" the condition line <= 5
pour one mug the loop body { ... }
count the mug line++ (the counter moves on)

while (condition) { body } checks the condition; if it is true it runs the body, then comes back and checks again. Each pass through the body is one iteration.

public class Main {
    public static void main(String[] args) {
        int line = 1;
        while (line <= 5) {
            System.out.println(line + ". I will not talk in class");
            line++;
        }
        System.out.println("Done! line is now " + line);
    }
}
1. I will not talk in class
2. I will not talk in class
3. I will not talk in class
4. I will not talk in class
5. I will not talk in class
Done! line is now 6

When line became 6, 6 <= 5 was false and the loop stopped. Change 5 to 100 (or 1000) and the code stays the same size, with the sentence written once.

The infinite loop trap

int count = 0;
while (count < 3) {
    System.out.println("Hello");
}

count never changes, so count < 3 is true forever: Hello, Hello, Hello... until the program is killed. This is an infinite loop; an online judge (and the SyntaxPilot compiler) stops it with Time Limit Exceeded. Every loop needs something that moves it towards the end:

int count = 0;
while (count < 3) {
    System.out.println("Hello");
    count++;
}
Hello
Hello
Hello

The for loop

Every counting loop has three parts: a start (int line = 1), a check (line <= 5) and a step (line++). In a while loop they're spread over three places, and forgetting one causes an infinite loop. Real-life example: a lap counter on a running track: start at lap 1, before each lap check "laps left?", after each lap add 1. The for loop puts all three in one line:

for (start; check; step) {
    body
}

Order of execution: start (once) → check → body → step → check → body → step → ... → check is false → leave.

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println("7 x " + i + " = " + 7 * i);
        }
    }
}
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

while or for?

Use When
for you know how many times (count from 1 to n, every index of an array)
while you repeat until something happens (until the user types 0, until a number becomes 0)
do-while the body must run at least once (menus, "try again?")

Off-by-one errors and scope

Off-by-one

Change i <= 10 to i < 10:

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

The output stops at 7 x 9 = 63. When i became 10, 10 < 10 was false. Running one round too few (or too many) is an off-by-one error. Always check the first and the last round.

Scope of the loop variable

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            System.out.println(i);
        }
        System.out.println("Last: " + i);
    }
}
Main.java:6: error: cannot find symbol
        System.out.println("Last: " + i);
                                      ^
  symbol:   variable i
  location: class Main
1 error

A variable declared in the for line (or inside any block) exists only inside that loop/block. Where a variable can be used is its scope. To use it afterwards, declare it before the loop: int i; for (i = 1; ...).

The accumulator pattern: sum of 1 to 100

public class Main {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        System.out.println("Sum: " + sum);
    }
}
Sum: 5050

An accumulator is a variable that collects a result across iterations: start it at 0 (or 1 for a product) before the loop, update it inside. Because it's declared outside, it survives after the loop.

do-while: the ATM menu

An ATM shows a menu, reads a choice, and repeats until you press 0. A while loop checks before the first round, but before the first round nothing has been chosen. The menu must show at least once. do { body } while (condition); runs the body first, then checks. Note the ; at the end.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int choice;
        do {
            System.out.println("1. Balance  2. Mini statement  0. Exit");
            choice = sc.nextInt();
            System.out.println("You chose " + choice);
        } while (choice != 0);
        System.out.println("Thank you for banking with us");
    }
}

Input 1, 2, 0:

1. Balance  2. Mini statement  0. Exit
You chose 1
1. Balance  2. Mini statement  0. Exit
You chose 2
1. Balance  2. Mini statement  0. Exit
You chose 0
Thank you for banking with us

while vs do-while when the condition is false from the start

public class Main {
    public static void main(String[] args) {
        int n = 10;
        while (n < 5) {
            System.out.println("while: " + n);
        }
        do {
            System.out.println("do-while: " + n);
        } while (n < 5);
    }
}
do-while: 10

A while loop can run zero times; a do-while always runs at least once.

break and continue

  • continue; skips the rest of this iteration and goes to the next one (a stale samosa: skip it, check the next).
  • break; leaves the loop completely (found your friend in the queue: stop looking).
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 1) {
                continue;
            }
            if (i > 8) {
                break;
            }
            System.out.print(i + " ");
        }
    }
}
2 4 6 8 

Odd numbers are skipped by continue; at 9 continue fires first, and at 10 break ends the loop. In a for loop, continue still runs the step (i++); in a while loop, a continue placed before the counter update skips it and can cause an infinite loop.

Nested loops: a star triangle

A loop inside another loop is a nested loop. For every iteration of the outer loop, the inner loop runs completely. Outer = rows, inner = columns.

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();
        }
    }
}
* 
* * 
* * * 
* * * * 

Row 1 prints 1 star, row 4 prints 4: the inner loop's check star <= row depends on the outer variable. Total inner iterations = 1 + 2 + 3 + 4 = 10.

The stray semicolon

public class Main {
    public static void main(String[] args) {
        int i;
        for (i = 1; i <= 5; i++); {
            System.out.println("Token " + i);
        }
    }
}
Token 6

The ; is the loop's entire (empty) body. The loop counts 1 to 6 doing nothing, then the block runs once with i == 6. Same trap as if (x); in episode 5.

Common mistakes (and the real messages)

Mistake Real result Why Fix
while (count < 3) { ... } with no count++ runs forever: Time Limit Exceeded nothing moves it to the end update the counter
for (int i = 1; i < 10; i++) for 10 rows one row missing off-by-one i <= 10; test the last round
using i after for (int i ...) cannot find symbol symbol: variable i i lives only inside the loop declare it before the loop
for (...); { ... } the block runs once the ; is the body no ; after the brackets
do { ... } while (x) without ; ';' expected do-while ends with a semicolon while (x);
int sum = 0; inside the loop sum is reset every round the accumulator must live outside declare it before the loop

Mini project: ATM PIN with 3 attempts

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int correctPin = 4321;
        boolean unlocked = false;
        for (int attempt = 1; attempt <= 3; attempt++) {
            System.out.println("Attempt " + attempt + ": enter PIN");
            int pin = sc.nextInt();
            if (pin == correctPin) {
                unlocked = true;
                break;
            }
            System.out.println("Wrong PIN");
        }
        if (unlocked) {
            System.out.println("Welcome! Balance: Rs 5000");
        } else {
            System.out.println("Card blocked");
        }
    }
}

Input 1111, 4321:

Attempt 1: enter PIN
Wrong PIN
Attempt 2: enter PIN
Welcome! Balance: Rs 5000

Input 1, 2, 3:

Attempt 1: enter PIN
Wrong PIN
Attempt 2: enter PIN
Wrong PIN
Attempt 3: enter PIN
Wrong PIN
Card blocked

The boolean flag unlocked remembers how the loop ended (break or ran out of attempts). Extend it: print how many attempts are left after each wrong PIN.

Practice

  1. Read a number n and print its multiplication table up to 10.
  2. Print the sum of the even numbers from 1 to 100.
  3. Read a number and count its digits with a while loop.
  4. Print this number pyramid for n = 4: 1, 1 2, 1 2 3, 1 2 3 4 (one per line).
  5. Read numbers until the user types 0, then print their sum (use do-while).
Solutions and hints
  1. for (int i = 1; i <= 10; i++) System.out.println(n + " x " + i + " = " + n * i);
  2. int s = 0; for (int i = 2; i <= 100; i += 2) { s += i; } gives 2550.
  3. java int count = 0; do { n = n / 10; count++; } while (n != 0); (do-while so that 0 counts as one digit.)
  4. Same shape as the star triangle: the inner loop prints col + " " instead of "* ".
  5. java int sum = 0, x; do { x = sc.nextInt(); sum += x; } while (x != 0); System.out.println(sum);

Quick quiz

What does this print?

for (int i = 0; i < 10; i += 3) {
    System.out.print(i + " ");
}
  • A. 0 3 6 9
  • B. 0 3 6
  • C. 3 6 9
  • D. 0 3 6 9 12
Answer

A. 0 3 6 9. i starts at 0 and goes up by 3. After 9 it becomes 12, and 12 < 10 is false, so the loop stops before printing 12.

Interview questions

  1. Difference between while and do-while? while checks first and may run zero times; do-while runs the body once before checking.
  2. What happens in for (;;) { }? All three parts are optional; an empty check means true, so it's an infinite loop (leave it with break).
  3. break vs continue? break exits the loop; continue skips to the next iteration.
  4. How do you break out of two nested loops at once? Use a labelled break (outer: for (...) { for (...) { break outer; } }) or a flag.
  5. How many times does the inner body run in two nested loops of n? n × n, which is why nested loops get slow for large n (you'll meet Big-O in the DSA episodes).
  6. What is an off-by-one error? A loop that runs one time too many or too few, usually < vs <= or starting at 0 vs 1.

Glossary

Term Meaning Example
loop code that repeats a block while a condition holds while, for, do-while
iteration one pass through the loop body the 3rd time the body runs
loop body the block a loop repeats { System.out.println(i); }
counter a variable that counts the rounds line++
while loop checks first, then runs the body, repeatedly while (line <= 5) { ... }
infinite loop a loop whose condition never becomes false no count++
for loop start, check and step in one line for (int i = 1; i <= 10; i++)
off-by-one error one round too many or too few i < 10 instead of i <= 10
scope the part of the code where a variable exists i only inside its for
accumulator a variable that collects a result over the rounds sum += i;
do-while loop runs the body first, then checks do { ... } while (choice != 0);
break leaves the loop immediately found the correct PIN
continue skips to the next iteration skip odd numbers
nested loop a loop inside another loop rows and columns of stars
flag a boolean that remembers something happened boolean unlocked

Summary

  • while (condition) checks, runs the body and repeats; something must change or it's an infinite loop.
  • for (start; check; step) keeps all three parts in one line.
  • Watch for off-by-one errors; a variable declared in a loop dies with the loop.
  • An accumulator starts before the loop and collects a result.
  • do { } while ( ); runs at least once; perfect for menus.
  • continue skips a round, break leaves the loop; nested loops draw patterns.

Next episode: arrays, so a loop can process a hundred values stored under one name.