C++ Break Statement

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.

Using a break, we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop or to force it to end before its natural end.

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:

  1. The loop prints numbers 1, 2 and 3.
  2. 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.

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:

  1. The switch statement evaluates the value of day.
  2. When day is 2, it matches case 2, and the corresponding block of code is executed.
  3. 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

C++ Break Statement – Interview Questions

Q 1: What is break statement?
Ans: It terminates loop or switch execution.
Q 2: Can break be used in if statement?
Ans: No.
Q 3: Does break exit nested loops?
Ans: Only the nearest loop.
Q 4: Is break mandatory in switch?
Ans: No, but recommended.
Q 5: Can break improve performance?
Ans: Yes, by exiting early.

C++ Break Statement – Objective Questions (MCQs)

Q1. What is the purpose of the break statement in C++?






Q2. What happens when a break statement is executed inside a loop?






Q3. In which of the following can the break statement be used?






Q4. What will be the output of the following code?

for(int i = 1; i <= 5; i++) {
if(i == 3)
break;
cout << i << " ";
}






Q5. In which of the following can the break statement be used?






Related C++ Break Statement Topics