Break and Continue Statements
Break and Continue statements are essential control flow statements that allow you to alter the flow of execution within loops. The break statement is used to exit a loop prematurely, and the continue statement is used to skip the current iteration and move to the next iteration. In this tutorial, we will explore how to effectively use break and continue statements in various loop scenarios.
Break Statement
The break statement is commonly used to terminate a loop prematurely. It allows you to exit the loop without completing all the remaining iterations. Here's an example of using the break statement within a for loop:
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 5; i++) {
if (i == 3) {
break; // Exit the loop when i equals 3
}
cout << "Iteration: " << i << endl;
}
return 0;
}
Ouput:
Iteration: 0
Iteration: 1
Iteration: 2
In this example, the loop terminates when i equals 3 because the break statement is encountered. As a result, the loop prematurely exits, and the remaining iterations are not executed.
Continue Statement
The continue statement is used to skip the rest of the current iteration and move to the next iteration of the loop. It is useful when a certain condition is met, and you want to skip specific statements within the loop. Consider the following example:
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue; // Skip iteration when i equals 2
}
cout << "Iteration: " << i << endl;
}
return 0;
}
Ouput:
Iteration: 0
Iteration: 1
Iteration: 3
Iteration: 4
In this example, when i equals 2, the continue statement is encountered, causing the loop to skip printing "Iteration: 2" and move directly to the next iteration.
Break and Continue statements are powerful tools for altering the flow of execution within loops. They allow you to exit a loop prematurely or skip the remaining statements of an iteration. By using these statements effectively, you can gain more control over your loops and make your programs more efficient. Practice using break and continue statements in different loop scenarios to better understand their versatility and impact on your code.
Basic Topics
- Introduction to C++
- Basic Syntax and Structure
- Variables
- Data Types
- Operators
- Output and Input
- Conditional Statements
- Loops
- Break and Continue Statements