Lesson 4 of 5 15 min read
Loops and iteration
Repeat work with for, while and do-while loops, loop over arrays, and avoid off-by-one and infinite loops.
In this lesson you will
- Write for, while and do-while loops and explain when to use each
- Iterate over an array with an index and with the enhanced for loop
- Use break and continue, and recognise off-by-one and infinite loops
Why loops?
Imagine printing the numbers 1 to 100. Writing 100 print statements is slow and error-prone. A loop repeats a block of code while a condition stays true.
The for loop
Use for when you know how many times to repeat:
for (int i = 1; i <= 5; i++) {
System.out.println("Step " + i);
}The header has three parts separated by semicolons:
- Initialisation
int i = 1runs once, before the loop starts. - Condition
i <= 5is checked before every repetition (an iteration). When it is false, the loop ends. - Update
i++runs after each iteration.
This prints Step 1 to Step 5.
A repeating cycle: Check i <= 5, then Run the body, then Update i++, then back to Check i <= 5
The while loop
Use while when you don't know in advance how many repetitions you need:
int balance = 1000;
int months = 0;
while (balance < 2000) {
balance = balance + balance * 10 / 100; // grows 10% each month
months++;
}
System.out.println("Months needed: " + months); // Months needed: 8The do-while loop
A do-while loop checks its condition after the body, so the body always runs at least once. It suits menus and input prompts:
int attempts = 0;
do {
attempts++;
System.out.println("Attempt " + attempts);
} while (attempts < 3);Looping over arrays
An array stores several values of the same type. Indexes start at 0.
int[] marks = {78, 92, 65, 88};
int sum = 0;
for (int i = 0; i < marks.length; i++) {
sum += marks[i];
}
System.out.println("Average: " + (double) sum / marks.length); // Average: 80.75
// Enhanced for loop: read each value without managing an index
for (int m : marks) {
if (m > 80) {
System.out.println(m + " is a distinction");
}
}(double) sum converts the total to a double so the division keeps its decimal part.
break and continue
breakexits the loop immediately.continueskips the rest of the current iteration and moves to the next one.
for (int n = 1; n <= 10; n++) {
if (n % 2 == 0) continue; // skip even numbers
if (n > 7) break; // stop after 7
System.out.println(n); // prints 1, 3, 5, 7
}Common mistakes
- Off-by-one errors: with an array of length 4, the valid indexes are 0 to 3. Writing
i <= marks.lengthtries to readmarks[4]and throws anArrayIndexOutOfBoundsException. - Infinite loops: if the condition never becomes false, the loop never ends. In
while (count < 10), forgettingcount++keepscountat its starting value forever.
Hands-on exercise
Write a program that prints the multiplication table of 7 from 7 × 1 to 7 × 10. Then, given int[] prices = {120, 450, 80, 999, 300}, use a loop to find and print the highest price without using any library method.
Knowledge check
3 questions • 70% to pass • Practice only, no certificate
Key concepts
- for suits a known number of repetitions; while suits repeating until something changes.
- do-while always runs its body at least once because the condition is checked afterwards.
- Array indexes run from 0 to length - 1; the enhanced for loop reads each element in turn.
- break leaves a loop, continue skips to the next iteration, and every loop needs a way to stop.
