Skip to content

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.

Beginner 15 min read·Lesson 11 of 39 in Java Programming

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

Java
while (condition) { ... }
do { ... } while (condition);
for (int i = 0; i < n; i++) { ... }
for (String name : names) { ... }
outer:
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
if (grid[r][c] == target) break outer;
  • 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--).
  • continue in a for loop still runs the update part.

Code examples

Four kinds of loop

Java
public class Loops {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) System.out.print(i + " ");
System.out.println();
int n = 1;
while (n < 100) n *= 3;
System.out.println("first power of 3 >= 100: " + n);
int tries = 0;
do {
tries++;
} while (tries < 3);
System.out.println("tries: " + tries);
int[] marks = {72, 88, 95};
int sum = 0;
for (int m : marks) sum += m;
System.out.println("sum: " + sum);
}
}
Output
1 2 3 4 5 
first power of 3 >= 100: 243
tries: 3
sum: 255

break and continue

Java
public class Skip {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) continue; // skip multiples of 3
if (i > 8) break; // stop after 8
System.out.print(i + " ");
}
System.out.println();
}
}
Output
1 2 4 5 7 8 

More examples

Nested loops, patterns and a labelled break

Java
public class Nested {
public static void main(String[] args) {
for (int row = 1; row <= 4; row++) {
System.out.println(" ".repeat(4 - row) + "*".repeat(2 * row - 1));
}
for (int i = 1; i <= 3; i++) {
StringBuilder line = new StringBuilder();
for (int j = 1; j <= 5; j++) line.append(String.format("%4d", i * j));
System.out.println(line);
}
int[][] grid = {{3, 8, 1}, {9, 4, 7}, {2, 6, 5}};
int target = 7, foundRow = -1, foundCol = -1;
search:
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] == target) {
foundRow = r;
foundCol = c;
break search;
}
}
}
System.out.println(target + " found at row " + foundRow + ", column " + foundCol);
}
}
Output
   *
  ***
 *****
*******
   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 r of the pyramid has 4 - r leading spaces and 2r - 1 stars; repeat builds each part.
  • The multiplication table uses an inner loop for columns; String.format("%4d", ...) right-aligns each product in 4 characters.
  • grid.length is the number of rows and grid[r].length the number of columns in row r.
  • search: labels the outer loop, so break 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:

TextOutput
*
***
*****
*******
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
7 found at row 1, column 2

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

for (int i = 0; i <= arr.length; i++) sum += arr[i];

Prefer

for (int i = 0; i < arr.length; i++) sum += arr[i];

Valid indexes are 0 to length - 1; the last iteration throws ArrayIndexOutOfBoundsException.

Forgetting to update the loop variable

Avoid

int i = 0;
while (i < 10) {
System.out.println(i);
}

Prefer

int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}

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

  1. 1
    Print all prime numbers below 100 using nested loops.
  2. 2
    Use 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?
Practise this topic