The break and continue statements in C++ are loop control statements used to change the normal flow of loops. They help manage program execution more efficiently.
What is break Statement?
The break statement is used to immediately terminate a loop or switch statement.
When break is executed:
- The loop stops instantly
- Control moves to the next statement after the loop
Syntax of break
break;
Example of break Statement
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
cout << i << endl;
}
return 0;
}
Output
1
2
3
4
The loop stops when i becomes 5.
What is continue Statement?
The continue statement skips the current iteration and moves to the next iteration of the loop.
When continue is executed:
- Remaining code inside the loop is skipped
- The next loop iteration begins immediately
Syntax of continue
continue;
Example of continue Statement
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
cout << i << endl;
}
return 0;
}
Output
1
2
4
5
The number 3 is skipped.
Difference Between break and continue
| break | continue |
|---|---|
| Stops the loop completely | Skips only current iteration |
| Exits loop immediately | Continues with next iteration |
| Used to terminate loops | Used to skip specific conditions |
Example Using while Loop
#include <iostream>
using namespace std;
int main() {
int i = 0;
while (i < 5) {
i++;
if (i == 2) {
continue;
}
if (i == 4) {
break;
}
cout << i << endl;
}
return 0;
}
Why break and continue are Important
These statements are important because they:
- Improve loop control
- Make code cleaner and more efficient
- Help avoid unnecessary iterations
- Simplify conditional logic
- Are widely used in real-world programs
Real-Life Example
break Example
Think of a fire alarm:
- Once the alarm rings, everyone immediately exits the building
- The process stops instantly
continue Example
Think of skipping absent students during attendance:
- Attendance continues
- Only one student is skipped
Conclusion
The break and continue statements in C++ are powerful loop control tools. break stops the loop completely, while continue skips the current iteration and continues execution. Both help make programs more efficient and easier to manage.