Break Statement In C++ - C++ Programming Tutorial
C++ Course / Control Flow / Break Statement In C++

Break Statement In C++

BLUF: Mastering Break Statement In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Break Statement In C++

C++ is renowned for its efficiency. Learn how Break Statement In C++ enables low-level control and high-performance computing in the tutorial below.

In C++, the break statement is employed to terminate loop or switch statements, interrupting the program's current flow based on a specified condition. If used within a nested loop, it will only exit the innermost loop.

In simpler terms, the break statement acts as a control flow mechanism in C++ programming, serving the purpose of prematurely ending loops and switch statements. By halting the closest loop or switch block, the break statement prevents the execution from proceeding to the subsequent statements. It is particularly useful for efficiently exiting loops and switch cases, enhancing both the performance and clarity of the code.

Syntax

It has the following syntax:

Example

jump-statement;      

break; 

//block of the code

Flow Diagram of Break Statement:

Basic Example of C++ Break Statement

Let's consider a simple example to demonstrate the usage of the break statement in C++.

Example

Example

#include <iostream>  

using namespace std;  

int main() {  

      for (int i = 1; i <= 10; i++)    

          {    

              if (i == 5)    

              {    

                  break; // Exit the loop when i reaches 5

              }    

        cout<<i<<"\n";    

          }    

}

Output:

Output

1

2

3

4

Working of Break Statement in C++

In this section, we will explore the application of break statements within various loop structures. Below are a few examples:

1. Simple Loops (for, while, do-while)

Loops are designed to conclude execution when a specific condition is met, whether it is in a for loop, a while loop, or a do-while loop. One common method to end a loop prematurely is by using the Break Statement, particularly in a for loop.

In C++, incorporating a break statement inside a for loop proves to be highly beneficial especially when the total number of iterations is predetermined.

Syntax:

It has the following syntax:

Example

for (initialization; condition; update) {

    if (break_condition) {  // 

        // Code to be executed before breaking

        break;  // Exits the loop

    }

    // remaining code to be executed if break condition is not met

}

Example:

Let's consider an example to demonstrate the use of the break statement with a for loop in the C++ programming language.

Example

Example

#include <iostream>

using namespace std;

int main() {

    for (int i = 1; i <= 10; i++) {

        if (i == 6) {

            cout << "Loop breaks at i = " << i << endl;

            break;  // Exit the loop when i reaches 5

        }

        cout << "i = " << i << endl;

    }

    

    cout << "Loop ended!" << endl;

    return 0;

}

Output:

Output

i = 1

i = 2

i = 3

i = 4

i = 5

Loop breaks at i = 6

Loop ended!

Explanation:

In this instance, a for loop is employed commencing at i=1 and running through to 10. The break statements come into play when i equals 6, causing an abrupt exit from the loop. Consequently, the values from 6 to 10 are not displayed as the loop ceases execution.

  • Using Break Statement with While Loop

In C++, incorporating a break statement inside a while loop proves to be highly beneficial when the iteration count is uncertain and contingent on a specific condition.

Syntax:

It has the following syntax:

Example

while (condition) {

    if (break_condition) {  // 

        // Code to be executed before breaking

        break;  // Exits the loop

    }

    // remaining code to be executed if break condition is not met

}

Example:

Let's consider a scenario to demonstrate the usage of the break statement with a while loop in the C++ programming language.

Example

Example

#include <iostream>

using namespace std;

int main() {

    int num, fact = 1;

    

    cout << "Enter a positive number: ";

    cin >> num;

    

    if (num < 0) {

        cout << "Factorial is not defined for negative numbers!" << endl;

        return 0; // Exit the program

    }

    int i = num;

    while (true) { // Infinite loop

        if (i == 0 || i == 1) {

            break;  // Exit the loop when i reaches 0 or 1

        }

        fact *= i;

        i--;

    }

    cout << "The Factorial of " << num << " is: " << fact << endl;

    return 0;

}

Output:

Output

Enter a positive number: 6

The Factorial of 6 is: 720

Explanation:

In this instance, the software prompts the user to enter a numerical value. If the input is negative, the loop terminates as calculating the factorial for negative numbers is not feasible. Following this, the program employs an infinite loop using while (true).

The break command halts the loop once it reaches the value of 1. Ultimately, the factorial computation involves multiplying numbers starting from num and descending to 1.

  • Terminating Loop Execution with do-while Statement

In the C++ programming language, a break statement inside a do-while loop will run at least once before evaluating the condition. This statement is helpful for terminating the loop early, irrespective of the condition.

Syntax:

It has the following syntax:

Example

do{ 

//Block of the code

if (break condition) {

break; //break Statement

   }

//execute remaining code block

   }

while(condition);

Example:

Let's consider an instance to demonstrate the break statement inside a do-while loop in C++.

Example

Example

#include <iostream>

using namespace std;

int main() {

    int i = 3;

    do {

        cout << "Iteration: " << i << endl;

        if (i == 5) {  // Condition to break the loop

            cout << "Break the loop at i = " << i << endl;

            break;

        }

        i++; // Increment counter

    } while (i <= 7);  // check the while loop condition

    cout << "Loop exited." << endl;

    return 0;

}

Output:

Output

Iteration: 3

Iteration: 4

Iteration: 5

Break the loop at i = 5

Loop exited.

Explanation:

In this instance, the do-while loop runs at least once prior to evaluating the condition, even if the condition is false initially. When the break_condition is met, the break statement promptly ends the loop iterations.

2. Break Statement with Nested Loops

In C++, the break statement can be employed when dealing with nested loops. When used within a nested loop, it specifically ends the innermost loop, causing the program flow to exit only from that particular loop.

Syntax:

It has the following syntax:

Example

for(initialization; condition; update) {  

    for(initialization; condition; update) {  

        if (condition) {  

            break;  // Exits the inner loop only

        }  

    }  

}

Example:

Let's consider a scenario to demonstrate the Break statement within a nested loop in C++.

Example

Example

#include <iostream>

using namespace std;

int main() {  

    for(int i = 1; i <= 3; i++) {         

        for(int j = 1; j <= 3; j++) {         

            if(i == 2 && j == 2) {         

                break;  // Breaks only the inner loop

            }         

            cout << i << " " << j << "\n";              

        }         

    }     

}

Output:

Output

1 1

1 2

1 3

2 1

3 1

3 2

3 3

3. C++ Break Statement with Inner Loop:

The C++ break statement interrupts the execution of the inner loop exclusively when employed within the inner loop.

Example

Example

#include <iostream>  

using namespace std;  

int main()  

{  

    for(int i=1;i<=3;i++){        

            for(int j=1;j<=3;j++){        

                if(i==2&&j==2){        

                    break;        

                        }        

                    cout<<i<<" "<<j<<"\n";             

                    }        

          }    

}

Output:

Output

1 1

1 2

1 3

2 1

3 1

3 2

3 3

4. Break statement with Infinity Loop

In C++, the break statement can be employed within an infinite loop alongside a condition to halt the execution of the endless loop.

Example

Example

#include <iostream>

using namespace std;

int main() {

    int count = 1;

    while (true) {  // Infinite loop

        cout << "Iteration: " << count << endl;

        if (count == 4) {  // Exit condition

            cout << "Breaking the loop..." << endl;

            break;  // Terminates the loop

        }

        count++;

    }

    cout << "Loop exited successfully." << endl;

    return 0;

}

Output:

Output

Iteration: 4

Breaking the loop...

Loop exited successfully.

Explanation:

In this instance, we demonstrate an infinite loop by employing a while(true) condition. Subsequently, the counter initiates at 1 and increments with each iteration. Upon reaching count == 4, the if statement is satisfied, leading to the execution of the break statement, which terminates the loop. Following this, the output is displayed on the console.

5. Break Statement in Switch Case:

In C++, the break statement within a switch case is employed to terminate the switch block upon executing a corresponding case. Absence of a break statement results in the execution flowing into the next case, known as fall-through behavior, typically undesirable.

Syntax:

It has the following syntax:

Example

switch(expression) {

    case value1:

        // Code to execute

        break;

    case value2:

        // Code to execute

        break;

    default:

        // Code to execute if no case matches

}

Example

Output:

Output

Choice is 2

Advantages of Break Statement:

Several advantages of Break statement in C++ are as follows:

  • Efficient code operation becomes possible because unnecessary iterations are stopped, which results in shorter execution time.
  • The statement indicates how to terminate execution to improve readability.
  • It enables loop termination at any time when the specified condition becomes true.
  • Conclusion

In summary, the flow of a program in C++ can be managed using the break statement, which offers a way to exit loops and switch cases based on specific conditions set within the program. Understanding the behavior of break statements in different coding scenarios plays a crucial role in optimizing code and enhancing operational performance. It is important to use break statements carefully to maintain code clarity and avoid ambiguity in programming.

Frequently Asked Questions (FAQs)

1. What function does the break statement serve in the C++ programming language?

The break command functions as a jump directive within C++ to prematurely exit both loops (for, while, do-while) and switch cases before they naturally conclude. This command halts the current loop or switch block immediately, allowing the program to move on to the next instruction. This feature enhances program efficiency by avoiding unnecessary iterations within loops.

2. What procedures does the break statement follow while operating inside nested loops?

When a break statement is encountered inside a nested loop, it will terminate only the innermost loop where it is situated. The outer loops will continue to execute unless they also contain break statements that meet specific conditions for execution. The break statement exclusively exits the immediate loop it is contained within, without impacting the execution of other loops in the hierarchy.

3. Which aspect makes C++ break different from continue statements?

The break and continue statements function differently because they modify loop sequences in C++:

  • A break statement stops the loop execution process by sending the command flow to the subsequent statement that follows the loop.
  • The continue statement triggers a loop to move immediately to its following iteration without finishing the present one.
  • Break allows a loop to end early when particular conditions exist, yet continuing allows a loop to skip specified iterations until the next cycle.
  • 4. Which function does the break statement serve within switch statement operations?

A switch statement necessitates the presence of the break statement to prevent unintended execution of subsequent cases. If the break statement is omitted, every case within a switch block will be executed, regardless of whether their conditions are met, leading to unpredictable results. Including a break statement after each case guarantees that the program exits the switch statement immediately after executing the corresponding condition.

5. What constraints exist when implementing the break statement?

The break statement comes with several usage restrictions.

  • For proper functioning, the break statement needs to appear within loops and switch statements; otherwise, a compilation error will occur.
  • Break statements can only leave the innermost loop when used in nested loops and so multiple loops require additional code for breaking.
  • Overuse of the break statement introduces confusion that makes debugging more difficult by disrupting the clear path of execution.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience