Break and Continue Statements in C++
The break
and continue
statements are used to alter the flow of loops. The break
statement terminates the loop, while the continue
statement skips the current iteration and moves to the next one.
Using the break
Statement
Example: Exiting a Loop Early
#include <iostream>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
std::cout << "Number: " << i << std::endl;
}
return 0;
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Using the continue
Statement
Example: Skipping an Iteration
#include <iostream>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
std::cout << "Number: " << i << std::endl;
}
return 0;
}
Output:
Number: 1
Number: 2
Number: 4
Number: 5
Key Takeaways
- The
break
statement exits the loop immediately. - The
continue
statement skips the current iteration and continues with the next one. - Use these statements to control loop execution based on conditions.