C++ Break and Continue Statement

There are two statements break; and continue; specifically to change the normal flow of a program.

Sometimes, it's desirable to skip the execution of a loop for a particular test condition or terminate it immediately on faith the condition.

C++ Break Statement


The break; statement terminates a loop and a switch statement immediately when it appears.

Syntax : -

break;


Example: -

#include <iostream>
using namespace std;

int main() {
int i = 1;
while(i <= 5)
{
if(i == 3)
{
break;
}
else
{
cout << i <<"\n";
}
}
}


Output:
1
2
In above Program, while loop is executed 5 times because condition is i <= 5.

But, when value of i is equal to 3 then the loop is terminates by the break statment and remain iteration of loop will not executed.


C++ Continue Statement


It is sometimes necessary to skip a certain test condition within a loop. In such case, continue; statement is used in C++.

Syntax : -

continue;


Example : -

#include <iostream>
using namespace std;

int main() {
int i = 1;
while(i <= 5)
{
if(i == 3)
{
continue;
}
else
{
cout << i <<"\n";
}
}
}


Output:
1
2
4
5
In above Program, while loop is executed 5 times because condition is i <= 5.

But, when value of i is equal to 3 then the loop is skip that iteration and program will not print 3 using continue statement.

Execution of remaining iteration will continue.