CodeBlanks Logo Icon CodeBlanks

break and continue

Learn to exit a loop with break and skip with continue.

break and continue

There are two ways to control loop flow: break exits the loop entirely, continue skips the current iteration and goes to the next. Both are used inside the loop body.

For example for (int i = 0; i < 10; i++) { if (i == 3) break; std::cout << i; } ends the loop when i is 3; the output is 012. Replacing break with continue skips i 3 and the output becomes 0134....

break vs continue

break and continue look similar but behave very differently. break ends the loop entirely and the program moves to the next statement. continue skips only the current iteration; if the condition still holds, the next iteration runs.

You use break when searching and the first match is found; you use continue to skip elements that meet a certain condition. In nested loops, break exits only the innermost loop; advanced code uses goto or a flag variable to work around this.

Practice Stop at 3 (break)

Inside a for (int i = 0; i < 10; i++) loop, stop the loop with if (i == 3) break;. On each iteration print i with std::cout << i;. The output must be 012.

Starter code

main.cpp
#include <iostream>

int main() {
    // Print with for and break
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    for (int i = 0; i < 10; i++) {
        if (i == 3) break;
        std::cout << i;
    }
    std::cout << std::endl;
    return 0;
}

Expected output

012

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each keyword to its effect

Term Meaning
break Exits the loop
continue Skips to next iteration
return Exits the function
throw Raises an exception

2 Write the continue keyword

Question
for (int i = 0; i < 5; i++) {
    if (i == 2) ____;
    std::cout << i;
}
Answer
for (int i = 0; i < 5; i++) {
    if (i == 2) continue;
    std::cout << i;
}

Explanation: continue skips printing when i == 2.

3 What is the output of this loop?

main.cpp
for (int i = 0; i < 5; i++) {
  if (i == 2) continue;
  std::cout << i;
}
  • 01234
  • 012
  • 0134 Correct answer
  • 234

Explanation: i = 2 is skipped; the output is 0134.

All lessons in Beginner