Module 3 · Control Flow and Arrays — topic 3 of 4
Loops
while, do-while, for and the enhanced for-each loop, break and continue, labelled breaks for nested loops, and choosing the right loop.
Learning objectives
- Choose between while, do-while, for and for-each
- Use break, continue and labelled break
- Write nested loops to process grids and patterns
Definition
A loop repeatedly executes a block of statements while a condition holds. Java provides while, do-while, the counting for loop and the enhanced for loop for arrays and collections.
Introduction
Computers are good at repetition. Loops let a program process every element of an array, retry until input is valid or simulate many steps of a game. Java has four loop forms, and choosing the right one makes your intent obvious to readers.
Why it matters
Almost every algorithm — searching, sorting, summing, counting — is built from loops.
Off-by-one errors and infinite loops are among the most common bugs, and they are easy to avoid with the right loop form.
Detailed explanation
while checks the condition first, so the body may run zero times. Use it when you don't know in advance how many iterations you need (reading until the input ends, waiting for a condition).
do-while runs the body once and then checks the condition, so it always runs at least once — ideal for menus and 'ask until valid' input.
for combines initialisation, condition and update: for (int i = 0; i < n; i++). Use it for counting loops. The loop variable exists only inside the loop.
for-each (enhanced for) visits each element of an array or collection: for (int x : marks). It is the clearest way to read every element, but it gives you no index and you can't use it to replace elements of an array.
break leaves the innermost loop immediately; continue skips to the next iteration. A label (outer:) before a loop lets break outer; leave several nested loops at once.
Infinite loops such as while (true) are fine when the body contains a break or return that is guaranteed to happen.
Syntax
- Use
i < array.length, not<=, to avoid going past the end. - Several variables can be updated in a for header:
for (int i = 0, j = n - 1; i < j; i++, j--). continuein a for loop still runs the update part.
Code examples
Four kinds of loop
1 2 3 4 5 first power of 3 >= 100: 243 tries: 3 sum: 255
break and continue
1 2 4 5 7 8
More examples
Nested loops, patterns and a labelled break
* *** ***** ******* 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 7 found at row 1, column 2
Step-by-step explanation
- Row
rof the pyramid has4 - rleading spaces and2r - 1stars;repeatbuilds each part. - The multiplication table uses an inner loop for columns;
String.format("%4d", ...)right-aligns each product in 4 characters. grid.lengthis the number of rows andgrid[r].lengththe number of columns in row r.search:labels the outer loop, sobreak search;leaves both loops as soon as the target is found.- If the target were missing, the row and column would stay -1, which the program could check for.
Expected output
Running “Nested loops, patterns and a labelled break” prints exactly:
Practical applications
- Processing every record in a file or list
- Retrying network requests a limited number of times
- Game loops that update and draw many times per second
- Scanning 2D grids such as images, boards and spreadsheets
Best practices
- Use for-each when you only need the elements.
- Keep loop bodies short; move complex work into methods.
- Prefer labelled break over boolean flags for leaving nested loops.
Common mistakes
Off-by-one with <=
Avoid
Prefer
Valid indexes are 0 to length - 1; the last iteration throws ArrayIndexOutOfBoundsException.
Forgetting to update the loop variable
Avoid
Prefer
Without the update the condition never becomes false and the loop runs forever.
Important notes
- Modifying a collection while iterating over it with for-each throws ConcurrentModificationException; use an Iterator's remove method or removeIf.
- Streams (module 9) offer an alternative to many loops, but plain loops remain clearer for simple tasks.
Key takeaways
- while may run zero times; do-while runs at least once.
- for is for counting; for-each is for visiting every element.
- break leaves a loop, continue skips an iteration, and labels target an outer loop.
Try it yourself
- 1Print all prime numbers below 100 using nested loops.
- 2Use a do-while loop to keep asking for a PIN until the correct one is entered or three attempts are used.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
7 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhat is printed?
- BeginnerWhat is printed?