Loop control
Sometimes a loop has to stop early or skip a single iteration. That is what break and continue are for, and for nested loops there are labels.
break
break ends the loop immediately, and the program continues with the code after it. It is a convenient way to stop a search as soon as the item is found:
void main() {
int[] numbers = {4, 7, 15, 8, 23};
for (int n : numbers) {
if (n > 10) {
IO.println("First number above 10: " + n);
break;
}
}
}Output:
First number above 10: 158 and 23 are never checked — the loop ended at 15.
continue
continue skips the rest of the current iteration and moves on to the next one. The loop keeps going:
void main() {
for (int i = 1; i <= 6; i++) {
if (i % 2 == 0) {
continue;
}
IO.print(i + " ");
}
IO.println();
}Output:
1 3 5For even i, continue fires and the output is skipped.
Nested loops
A loop inside a loop is called nested. The inner loop runs completely on every iteration of the outer one:
void main() {
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
IO.print(row * col + "\t");
}
IO.println();
}
}Output:
1 2 3
2 4 6
3 6 9break and continue affect only the loop they are written in — that is, the innermost one.
Labels
To leave the outer loop at once, mark it with a label — a name with a colon before the loop — and write break with that name:
void main() {
int[][] seats = {{0, 0, 1}, {0, 1, 0}};
search:
for (int row = 0; row < seats.length; row++) {
for (int col = 0; col < seats[row].length; col++) {
if (seats[row][col] == 1) {
IO.println("Taken: row " + row + ", seat " + col);
break search;
}
}
}
}Output:
Taken: row 0, seat 2Here seats is a two-dimensional array — an array of rows where 1 marks a taken seat; such arrays have their own lesson. Without the label, break would stop only the inner loop, and the search would go on into the second row. continue with a label works the same way — it jumps to the next iteration of the labeled loop.
Exiting from the middle
A while (true) loop never ends by itself. It is used when the exit condition is easiest to check in the middle of the body, and you leave with break:
void main() {
int balance = 100;
while (true) {
balance -= 30;
if (balance < 0) {
break;
}
IO.println("Balance: " + balance);
}
}Output:
Balance: 70
Balance: 40
Balance: 10Common mistake
In a while loop you update the counter by hand. If continue comes before that update, the counter gets stuck on one value and the loop never ends:
int i = 0;
while (i < 5) {
if (i == 2) {
continue; // i++ below never runs again
}
IO.println(i);
i++;
}The program prints 0 and 1 and then hangs. Update the counter before continue, or use for, where the i++ step runs even after continue.