×

C++ Break

In this article, we will discuss the C++ Break statement with its syntax, algorithm, pseudocode, and examples.

The C++ break statement also terminates the currently active loop or switch statement immediately. It causes the program to leave the current loop or switch block and resume at the statement immediately following the loop or switch.

Syntax:

It has the following syntax:

Break;

Break statement in C++

  • Loops (for, while, and do-while): These loops are used to break out of the loop early when a specific condition is satisfied.
  • Switch Statements: This statement is used to stop case labels from falling through.

The break statement where it is used mostly:

  • Exiting loops: When a specific condition is satisfied inside the loop, the break function can be used to terminate the loop and prevent further iterations.
  • Breaking out of a switch Statement: Break makes sure that the software doesn’t carry out future cases after a case is ended.

Algorithm for Break statement in a loop:

  • Start the program.
  • Initialize a loop (e.g., for, while, or do-while).
  • Inside the loop, check a condition to determine if break should be executed.
  • If the condition is met, execute break to exit the loop.
  • Continue execution of the program after the loop.
  • End the program.

Pseudo code for Break statement in a loop:

Begin

  For i = 1 to 10 do

    Print i

    If i == 5 then

      Print "Breaking the loop at i = 5"

      Break // Exit the loop

    Endif

  Endfor

End

Key Aspects:

  1. It is utilized for stopping iterations within while, do-while, and for loops.
  2. It is used in switch statements to prevent fall-through.
  3. Wherever it is placed, it only exits the innermost switch or loop.
  4. It exclusively sets a stop to execution at a certain point; conditional statements remain intact.

Usage of break statement in Loops:

A loop is terminated immediately when a break statement is used in the loop. Control goes to the statement immediately following the loop.

Example 1:

Let us take an example to illustrate the break statement in C++.

#include <iostream>

using namespace std;

int main() {

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

        if (i == 3) {

            break;  // Exits the loop when i is 3

        }

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

    }

    cout << "Loop exited!" << endl;

    return 0;

}

Output:

Iteration: 1

Iteration: 2

Loop exited!

Example 2:

Let us take another example to illustrate the break statement in C++.

#include <iostream>

using namespace std;

int main() {

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

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

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

            break;  // Exits the loop when i equals 5

        }

        cout << i << " ";

    }

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

    return 0;

}

Output:

1 2 3 4 Breaking the loop at i = 5

Loop exited successfully.

Algorithm for Break statement in Switch case:

  • Start the program.
  • Accept an input choice.
  • Use a switch statement to check the value of the input.
  • If a case matches the input value:
  • Execute the corresponding block of statements.
  • Use break to prevent execution of the next case.
  • If no cases match, execute the default case.
  • End the program.

Pseudo code for Break statement in Switch case:

Begin

  Read choice

  Switch (choice) DO

    CASE 1:

      Print "Choice is 1"

      Break

    CASE 2:

      Print "Choice is 2"

      Break

    CASE 3:

      Print "Choice is 3"

            Break

    Default:

      Print "Invalid choice"

  End Switch

End

Example 1: Usage of break statement in the switch case

Let us take an example to illustrate the break statement using switch case in C++.

#include <iostream>

using namespace std;

int main() {

    int choice = 2;


    switch (choice) {

        case 1:

            cout << "Choice is 1
";

            break;

        case 2:

            cout << "Choice is 2
";

            break;

        case 3:

            cout << "Choice is 3
";

            break;

        default:

            cout << "Invalid choice
";

    }

    return 0;

}

Output:

Choice is 2

Example 2:

Let us take another example to illustrate the break statement using switch case in C++.

#include <iostream>

using namespace std;


int main() {

    int choice;

    cout << "Enter a number (1-3): ";

    cin >> choice;

    switch (choice) {

        case 1:

            cout << "You selected option 1." << endl;

            break;

        case 2:

            cout << "You selected option 2." << endl;

            break;

        case 3:

            cout << "You selected option 3." << endl;

            break;

        default:

            cout << "Invalid choice!" << endl;

    }

    cout << "Switch statement completed." << endl;

    return 0;

}

Output:

Enter a number (1-3): 2

You selected option 2.

Switch statement completed.

If there were no break, execution would go on to the following case, resulting in different manner.

Conclusion:

In conclusion, the break statement in C++ is a very strong control flow tool that allows programmers to terminate their loops and switch statements very quickly, hence avoiding unnecessary iterations and ensuring proper logical execution. The use of break in switch statements is essentially meant to control the flow of the program because it ensures that only the matched case gets executed while guarding against unintended fall-through to subsequent cases. It also prevents the iteration of loops when a certain condition is satisfied. Breaks are required in structured programming, but not too much in order to keep clarity in codes and an avoidance of immediate exits.


Related Topics

C++ storage classes

Storage Classes are used to characterize a variable's or function's characteristics. These characteristics include scope, visibility, and life-time, which allow us to track the presence of a variable over the...

5 minutes read.

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

Object Slicing in C++

In this article, we will learn about Object slicing. When an object from a derived class is assigned to an object from a base class in C++, these extra attributes...

3 minutes read.

Destructor

Let’s discover the C++ destructor, virtual and pure virtual destructors, and when destructors are invoked and their rules in this lesson. Destructors : A member function that destroys an object is known as...

5 minutes read.

Processing strings using std string stream in C++

A string class object called std: string stream is used to streamline into various variables, just as files can pour into strings. This class's things make use of a string...

3 minutes read.

Quick Sort in C++

Quick sort is an efficient, in-place, comparison-based sorting algorithm that uses a divide-and-conquer strategy to sort an array or list of elements. First a pivot element is selected from the...

4 minutes read.

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

Reverse function in C++

The function std::reverse() is included in the standard template library of C++. It takes in a beginning and ending iterator, reversing the order. To use the reverse statement, we need...

2 minutes read.

fread() Function in C++ Programming

C++ language is used to make high-performance applications that can work efficiently, and it is one of the world's most popular languages. It is an object-oriented and high-level programming language;...

3 minutes read.

C++ Program to Print Fibonacci Triangle

Fibonacci Triangle Program in CPP Definition: Fibonacci Triangle as the name suggests is the same as the Fibonacci number series where the next element is the sum of the previous two elements....

3 minutes read.

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples. C++ Standard Input/Output: User-program communication is made possible by C++’s usage of input and output (I/O)...

5 minutes read.

Difference between Exit and Return

Define Exit() At the point when a client needs to leave a program from this capability is utilized. A void return type capability calls all capabilities enrolled at the exit and ends...

3 minutes read.

LCM Program in C++

What is LCM? LCM is an acronym for "least common multiple". It is used to discover the lowest positive integer divisible by all integers (whose LCM is calculated). For instance, the...

4 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

Stringstream in C++ and its applications

In this tutorial, we will explore what the stringstream in C++ is. We will also learn its application. What is stringstream? With the aid of a stringstream, user can read from a...

2 minutes read.

Upcasting and Downcasting in C++

With the help of various examples in the C++ programming language, this section will cover Upcasting and Downcasting. Upcasting and downcasting, on the other hand, are two forms of object typecasting. Consider...

3 minutes read.

C++ String Concatenation

C++ String Concatenation In this section, we will learn about C ++ String Concatenation, what it does, how it works, and will also see its programs. What is the String Concatenation? The + operator...

3 minutes read.

Data Hiding in C++

C++ : High-performance apps can be made using the cross-platform language C++. Bjarne Stroustrup created C++ as an addition to the C language. Programmers have extensive control over memory and system...

3 minutes read.

Palindrome using For loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.