Loops
A loop repeats a block of code. Without loops, processing a list of 1000 records would require writing the same code 1000 times. Loops are how programs do real work at scale.
The for Loop
The for loop is best when you know in advance how many times to repeat. Its header has three parts: initialisation, condition, and update — all in one line.
// Basic counting loop
for (int i = 1; i <= 10; i++) {
System.out.println("Iteration: " + i);
}
// Anatomy:
// int i = 1 — runs ONCE before the loop starts (initialise counter)
// i <= 10 — checked BEFORE each iteration (continue if true)
// i++ — runs AFTER each iteration (update counter)
// Counting down
for (int i = 10; i >= 1; i--) {
System.out.print(i + " ");
}
System.out.println("Lift off!");
// Stepping by more than 1
for (int i = 0; i <= 100; i += 10) {
System.out.print(i + " "); // 0 10 20 30 40 50 60 70 80 90 100
}
Nested for Loops
Place one loop inside another to iterate over two dimensions — rows and columns, or to build multiplication tables.
// Multiplication table (5×5)
System.out.println("--- Multiplication Table ---");
for (int row = 1; row <= 5; row++) {
for (int col = 1; col <= 5; col++) {
System.out.printf("%4d", row * col); // printf for aligned output
}
System.out.println(); // new line after each row
}
// Output:
// 1 2 3 4 5
// 2 4 6 8 10
// 3 6 9 12 15
// 4 8 12 16 20
// 5 10 15 20 25
The while Loop
The while loop is best when you don't know in advance how many iterations you need — only the condition that should stop it. The body might run zero times if the condition is false from the start.
// Countdown with decreasing balance
int balance = 1000;
int withdrawal = 250;
while (balance > 0) {
System.out.println("Current balance: R" + balance);
balance -= withdrawal;
}
System.out.println("Account empty.");
// Reading input until valid (common real-world pattern)
java.util.Scanner scanner = new java.util.Scanner(System.in);
int mark = -1;
while (mark < 0 || mark > 100) {
System.out.print("Enter a mark (0-100): ");
mark = scanner.nextInt();
if (mark < 0 || mark > 100) {
System.out.println("Invalid. Please enter a number between 0 and 100.");
}
}
System.out.println("Valid mark entered: " + mark);
The do-while Loop
Like a while loop, but the body runs at least once before checking the condition. Use it when you always need at least one execution — like showing a menu.
int attempts = 0;
int maxAttempts = 3;
boolean success = false;
do {
attempts++;
System.out.println("Attempt " + attempts + " of " + maxAttempts);
// Simulate checking a password
success = (attempts == 2); // succeeds on attempt 2 for demo
} while (!success && attempts < maxAttempts);
if (success) {
System.out.println("Login successful!");
} else {
System.out.println("Account locked after " + maxAttempts + " failed attempts.");
}
The for-each Loop
The for-each loop (enhanced for) iterates over every element in an array or collection without managing an index. Use it when you need the values but not the positions.
int[] marks = {65, 72, 80, 58, 91, 44, 77};
// for-each — clean and unambiguous
int total = 0;
for (int mark : marks) {
total += mark;
System.out.println("Mark: " + mark);
}
System.out.println("Average: " + (double) total / marks.length);
// When you need the index — use regular for
for (int i = 0; i < marks.length; i++) {
System.out.println("Learner " + (i + 1) + ": " + marks[i] + "%");
}
break and continue
// break — immediately exit the loop
for (int i = 1; i <= 100; i++) {
if (i == 6) break; // stop as soon as we reach 6
System.out.print(i + " "); // prints 1 2 3 4 5
}
System.out.println();
// continue — skip the rest of this iteration, go to next
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip even numbers
System.out.print(i + " "); // prints 1 3 5 7 9
}
Practice Task
Your Turn
Write three programs: (1) Use a for loop to print the first 20 Fibonacci numbers (each is the sum of the two before it). (2) Use a while loop to find the first power of 2 that exceeds 1000. (3) Use nested for loops to print a right-angled triangle of asterisks that is 6 rows tall (row 1 has 1 star, row 6 has 6 stars).
Common Mistakes
- Infinite loop — if the condition never becomes false, the program hangs forever. Always verify that the loop variable moves toward making the condition false.
- Off-by-one errors —
i < lengthvsi <= length. Draw out the first and last iterations manually. - Placing a semicolon directly after
for(...)creates an empty loop body — the code block below runs only once after all iterations complete. - Modifying an array inside a for-each loop does not affect the original array — for-each gives you a copy of each element.
- Nested loop variable names — both loops using
icauses the outerito be hidden. Userowandcoloriandj.
Professional Tip
When writing a loop, write the condition that stops it first, then the body. Ask: what state must be true for the loop to end? Make sure your code moves toward that state with every iteration.
Mini Quiz
Which loop always executes its body at least once?