Break and Continue in C++

Break and continue in c++. Break is a loop control statement in C or C++ that is used to end the loop. The loop iterations stop as soon as the break statement is encountered within a loop, and control returns from the loop to the first statement after the loop. A break occurs when a loop is broken rather than when an if statement is broken. Only loops and switch statements are affected by a break statement. In any programming language, if is not a loop.

Break Statement in C++

The break statement stops the execution of the next enclosing do, for, switch, or while statement it appears in. The control is passed to the next statement after the terminated statement.

#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 5; i++)
{
if (i == 2)
{
break;
}
cout << i << "\n";
}
return 0;
}

 

Output:

0

1

Continue Statement in C++

The continue statement is similar to the break statement in how it operates. Continue, on the other hand, instead of forcing termination, forces the next iteration of the loop to run, skipping any code in between. The conditional test and increment portions of the for loop are executed when you press continue in the for loop. The continue statement is the polar opposite of the break statement in that it forces the loop to execute the next iteration rather than terminating it. The continue statement, as its name implies, forces the loop to continue or execute the next iteration.

#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 5; i++)
{
if (i == 2)
{
continue;
}
cout << i << "\n";
}
return 0;
}

 

Output:

0

1

3

4