Card 08/ 09

ExerciseDifficulty: Intermediate1 min

break or continue: Write Down What Prints

Two loops over the same five numbers, differing in one keyword. Write down both outputs in full before you open the reveal.

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 goes on to the next one, so three is skipped and four and five still print. break abandons the loop entirely, so nothing after three runs at all.

The part worth holding: continue in a counted for 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 it and the loop never ends.