Mark As Completed Discussion

Breaking and Continuing

In programming, breaking out of a loop means prematurely terminating the loop and moving on to the next line of code after the loop. Continuing, on the other hand, means skipping the current iteration of the loop and moving on to the next iteration.

This can be useful when you want to exit a loop early or skip certain iterations based on specific conditions.

Let's take a look at an example in C++. In this example, we have a for loop that iterates from 1 to 10. But when the loop variable i is equal to 5, we use the continue statement to skip that iteration and move on to the next iteration.

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5  for (int i = 1; i <= 10; i++) {
6    if (i == 5) {
7      continue;
8    }
9    cout << i << " ";
10  }
11
12  return 0;
13}

The output of this code will be:

SNIPPET
11 2 3 4 6 7 8 9 10

As you can see, when i is equal to 5, the continue statement is executed, and that iteration is skipped.

You can use the break statement to completely exit a loop when a certain condition is met. This is useful when you want to stop the loop execution prematurely based on a certain condition.

Try running the code and observe the output to see how the continue statement works in skipping iterations.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment