Unit 2 · Java Fundamentals · 9 min
Loops: for, while, do-while
A loop repeats a block of statements until a condition becomes false, so you do not have to copy-paste the same code.
Why this matters
Printing tables, summing marks, scanning arrays — almost every useful program repeats something.
Syntax
Syntax
for (initialisation; condition; update) { ... }
while (condition) { ... }
do { ... } while (condition);Example
Java
public class Loops {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("5 x " + i + " = " + (5 * i));
}
int count = 3;
while (count > 0) {
System.out.println("Countdown: " + count);
count--;
}
int n = 0;
do {
System.out.println("Runs at least once, n = " + n);
} while (n > 0);
}
}Output
5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 Countdown: 3 Countdown: 2 Countdown: 1 Runs at least once, n = 0
Step by step
- 1`int i = 1` runs once at the start.
- 2`i <= 5` is checked before every repetition; when false the loop ends.
- 3`i++` runs after each repetition.
- 4`while` checks the condition first, so it may run zero times.
- 5`do-while` runs the body first and checks afterwards, so it always runs at least once.
Key points
- for is best when you know how many repetitions you need
- while is best when you repeat until something happens
- do-while always executes at least once
- break exits a loop, continue skips to the next repetition
Common mistakes
- Forgetting i++ and creating an infinite loop
- Using <= where < was needed (off-by-one errors)
- Declaring i inside the loop body and losing it every round
Try it yourself
- Print the multiplication table of a number entered by the user.
- Find the sum of the first 10 natural numbers with a while loop.