Card 08/ 09

ExerciseDifficulty: Intermediate1 min

Practice: Predicting What break and continue Do

Two loops differ by one keyword; write down both outputs before you look.

break and continue are the two keywords that change a loop's course from inside its body, and this exercise practises telling them apart. break ends the whole loop. continue ends only the current pass, and the loop goes on with the next one.

The two loops below count from 1 to 5 and differ in one keyword. Write down what each one prints, in full, before you open the answer.

java
for (int i = 1; i <= 5; i++) {
    if (i == 3) { continue; }
    System.out.print(i);
}
System.out.println();

for (int i = 1; i <= 5; i++) {
    if (i == 3) { break; }
    System.out.print(i);
}
Both outputs, and what each keyword did
text
1245
12

continue abandons the rest of this pass and moves to the next one, so 3 is skipped and 4 and 5 still print. break abandons the loop entirely, so nothing from 3 onwards runs at all.

In a counted for, continue still runs the i++, because the increment belongs to the loop rather than to the body. Written as a while with the increment at the bottom of the body, the same continue skips the increment, i stays at 3, and the loop never ends.