In C++, the break statement is used to immediately exit from a loop or switch statement, regardless of the loop’s condition or remaining iterations. It effectively “breaks” out of the loop and transfers control to the code that follows the loop.
Syntax:
break;
Where we can use break statement?
1. Loops: In for, while, and do-while loops.
2. Switch statements: To exit the switch block after a case is executed.
Example: use break statement in for loop
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 4) {
break; // Exit the loop when i is 4
}
cout << i << endl;
}
cout << "Loop terminated."<< endl;
return 0;
}
Explanation:
- The loop prints numbers 1, 2 and 3.
- When i becomes 4, the break statement exits the loop, and the program continues with the statement after the loop.
Output:
1
2
3
Loop terminated.
2
3
Loop terminated.
Example: use break statement in switch statement
#include <iostream>
using namespace std;
int main() {
int day = 2;
switch(day) {
case 1:
cout << "Sunday" << endl;
break;
case 2:
cout << "Monday" << endl;
break;
case 3:
cout << "Tuesday" << endl;
break;
default:
cout << "Not find day" << endl;
}
return 0;
}
Explanation:
- The switch statement evaluates the value of day.
- When day is 2, it matches case 2, and the corresponding block of code is executed.
- The break statement ensures that after executing the matching case, control exits the switch statement and continues with the code after the switch.
Output:
Monday