C++ Break and Continue
In C++, break
and continue
are control flow statements used within loops to alter their normal execution:
1. Break Statement
The break
statement is used to terminate the loop immediately when a certain condition is met:
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
if (i == 3) {
break;
}
std::cout << "Iteration " << i << std::endl;
}
return 0;
}
2. Continue Statement
The continue
statement is used to skip the remaining code inside the loop for the current iteration and proceed to the next iteration:
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
if (i == 3) {
continue;
}
std::cout << "Iteration " << i << std::endl;
}
return 0;
}
3. Using Break in Nested Loops
Example of using break
in nested loops:
#include <iostream>
int main() {
for (int i = 1; i <= 3; ++i) {
for (int j = 1; j <= 3; ++j) {
if (j == 2) {
break; // Exit inner loop when j equals 2
}
std::cout << "(" << i << ", " << j << ") ";
}
std::cout << std::endl;
}
return 0;
}
4. Using Continue in Nested Loops
Example of using continue
in nested loops:
#include <iostream>
int main() {
for (int i = 1; i <= 3; ++i) {
for (int j = 1; j <= 3; ++j) {
if (j == 2) {
continue; // Skip iteration when j equals 2
}
std::cout << "(" << i << ", " << j << ") ";
}
std::cout << std::endl;
}
return 0;
}
Conclusion
break
and continue
statements provide flexibility and control within loops in C++. This chapter covered their usage to terminate a loop prematurely or skip an iteration based on specified conditions. Mastering these statements allows you to write more efficient and responsive loop constructs in your programs.