08 Feb break and continue in C++
Repeatedly execute a block of code using the loop control statements in C++. The following are the loop control statements in C++:
- break statement
- continue statement
C++ break statement
Use the break statement if you want to jump out of a loop. The control passes to the first statement after the loop, since the break statement terminates the loop.
The syntax for the break statement in C++:
1 2 3 |
break; |
The following is an example of implementing the break statement in C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// break statement in C++ // Code by Studyopedia #include <iostream> using namespace std; int main() { int i = 5; while (i < 10) { cout << "i = " << i << endl; i++; // i = i + 1 if (i > 7) { break; } } return 0; } |
Here is the output:
1 2 3 4 5 |
i = 5 i = 6 i = 7 |
The above C++ code uses a while loop to iterate while i is less than 10. It prints the value of i and increments it. If i becomes greater than 7, the break statement exits the loop. The loop terminates early when i exceeds 7, even though the condition i < 10 is still true.
C++ continue statement
Use the continue statement if you want to pass control to the next iteration of the loop. However, it skips any code in between.
The syntax for the continue statement in C++:
1 2 3 |
continue; |
The following is an example of implementing the continue statement in C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// continue statement in C++ // Code by Studyopedia #include <iostream> using namespace std; int main() { int i = 100; do { if (i == 110) { i = i + 1; continue; } cout << i << endl; i++; } while (i < 115); return 0; } |
Here is the output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
100 101 102 103 104 105 106 107 108 109 111 112 113 114 |
The above C++ code iterates from 100 to 114 using a do-while loop. If i is 110, the loop skips the current iteration, increments i, and continues with the next iteration. For all other values of i, it prints i and then increments it. The loop stops when i reaches 115.
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others:
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments