C++ break statement
C++ break statement
The break statement in C++ is used to immediately terminate a loop or a switch statement. After the break statement executes, control moves to the first statement following the loop or switch.
Syntax
break;
Example 1: break in a for Loop
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break;
}
cout << i << " ";
}
return 0;
}
Output:
1 2 3 4 5
Explanation: The loop stops when i becomes
6, so numbers after 5 are not printed.
Example 2: break in a while Loop
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 10) {
if (i == 4) {
break;
}
cout << i << " ";
i++;
}
return 0;
}
Output:
1 2 3
Example 3: break in a switch Statement
#include <iostream>
using namespace std;
int main() {
int choice = 2;
switch (choice) {
case 1:
cout << "One";
break;
case 2:
cout << "Two";
break;
case 3:
cout << "Three";
break;
default:
cout << "Invalid choice";
}
return 0;
}
Output:
Two
Explanation: The break statement prevents
execution from continuing into the next case (known as
fall-through).
Key Points
- Exits the nearest enclosing loop or
switchstatement. - Used to stop a loop early when a condition is met.
- In nested loops,
breakexits only the innermost loop.
Nested Loop Example
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2)
break;
cout << "(" << i << "," << j << ") ";
}
}
return 0;
}
Output:
(1,1) (2,1) (3,1)
Here, the break statement exits only the inner
for loop, while the outer loop continues executing.