C++ Break and Continue

The break statement

The break statement in C++ is used to immediately exit a loop. When the break statement is executed, the program control is transferred to the next statement outside the loop. This statement is often used to stop an infinite loop, or to exit a loop when a certain condition is met.

Here is an example of using the break statement in a while loop to exit the loop when a certain condition is met:

#include <iostream>
using namespace std;

int main() {
   int i = 1;
   while (i <= 10) {
      if (i == 5) {
         break;
      }
      cout << i << endl;
      i++;
   }
   return 0;
}

Output:

1
2
3
4

In the above example, the while loop runs from 1 to 10. When the value of i is equal to 5, the break statement is executed, and the loop is immediately exited.

C++ Continue Statement

The continue statement in C++ is used to skip the remaining statements in the current iteration of a loop and move on to the next iteration. This statement is often used to skip certain values or conditions that are not needed in the loop.

Here is an example of using the continue statement in a for loop to skip even numbers:

#include <iostream>
using namespace std;

int main() {
   for (int i = 1; i <= 10; i++) {
      if (i % 2 == 0) {
         continue;
      }
      cout << i << endl;
   }
   return 0;
}

Output:

1
3
5
7
9

In the above example, the for loop runs from 1 to 10. When the value of i is even, the continue statement is executed, and the remaining statements in the loop are skipped for that iteration.

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial