← C++ from Scratch Lesson 20 of 62 · 10 XP

break and continue

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

  • break — leave the loop straight away;
  • continue — skip the rest of the body and go on to the next step.
for (int i = 1; i <= 10; i++) {
    if (i % 3 == 0) continue;   // skip multiples of 3
    if (i > 7) break;           // don't go past 7
    std::cout << i << ' ';      // 1 2 4 5 7
}

break leaves only the nearest loop. To get out of two nested loops, people use a flag or move the loops into a function and return.

Task. Read numbers one at a time. Skip negative ones, and stop at the number 0. Print the sum of the non-negative numbers before the zero.

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