← Java from Scratch Lesson 19 of 88 · 10 XP

break and continue

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

  • break — leave the loop;
  • continue — go on to the next iteration.
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) continue;
    if (i > 7) break;
    System.out.print(i + " ");    // 1 3 5 7
}

To leave nested loops all at once, use a label:

outer:
for (int y = 0; y < 10; y++)
    for (int x = 0; x < 10; x++)
        if (grid[y][x] == target) break outer;

Task. Read integers. Skip negative ones, and stop at 0 (numbers after the zero don't count). Print the sum and the count of the numbers that were counted, separated by a space.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.