How to use break and continue in C++
Break and continue are loop control statements in C++ that are used to exit from the loop or skip any iteration in the loop.
Break
The break statement is used to terminate the loop. As soon as a break statement is executed within the loop, the loop iteration stops and the very next statement after the loop starts executing.
Syntax
break;
The flow of a break statement is illustrated in the diagram below.
The break statement can be implemented in 3 types of loops:
- simple loop
- nested loop
- infinite loop
In a simple loop, the code right after the loop executes upon encountering a break statement.
#include <iostream>using namespace std;int main() {cout << "Before loop" << endl;for (int i=0 ; i<10 ; i++){cout << i << endl;if(i==5){break;}}cout << "After loop";return 0;}
In a nested loop, a break statement only terminates the innermost loop.
#include <iostream>using namespace std;int main() {cout << "Before loop" << endl;for (int i=0 ; i<10 ; i++){cout << "i: " << i << endl;for (int j =0 ; j< 3 ; j++){cout << "j: " << j << endl;if(j==1){cout << "using break ----" << endl;break;}}}cout << "After loop";return 0;}
In an infinite loop, the break statement is used to terminate the loop and exit the infinite loop.
#include <iostream>using namespace std;int main() {int i = 0 ;while(1){cout << "i:" << i << endl;if(i==15){cout << "using break----" << endl;break;}i++;}}
Continue
A continue statement, just like a break statement, is a loop control statement. Instead of terminating the loop and exiting from it, the continue statement forces the loop to skip the current iteration and continue from the next iteration.
Syntax
continue;
The flow of a continue statement is illustrated in the diagram below.
An example of the continue statement is given below.
#include <iostream>using namespace std;int main() {// your code goes herefor (int i=1; i<=10 ; i++){if(i%2==0){cout <<"missing itertionusing continue statement" << endl;continue;}cout << i << endl;}return 0;}