×

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

Virtual class in C++

Introduction to Virtual Base class Virtual base classes can be utilized in virtual inheritance as a mechanism for examining many "instances" of a certain class while searching through multiple inheritances in...

6 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.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

Approach in C++

Object oriented programming languages like Java or C++ use a bottom-up approach that identifies each object first.  In the bottom-up approach, we create a small problem first, and try to...

6 minutes read.

C++ Namespaces

An Overview In each scope, a name can only represent one entity. As a result, there cannot be two independent variables with the similar names in the same scope, as this may cause...

10 minutes read.

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be...

3 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

Decimal to Binary in C++

What is the meaning of Decimal Numbers? Decimal numbers range from 0 to 9, there are a total of ten digits between 0 and 9. Any number with more than two...

3 minutes read.

Difference between C and C++

What do you mean by C? C is a machine-independent structure or procedural oriented computer language that is widely utilized in a variety of applications. C is a fundamental programming language...

4 minutes read.

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

Binary Search in C++

The binary search in the C++ programming language will be discussed. By continually halves the array and then seeking specified items from a half array; binary search is a technique...

8 minutes read.

Classes and Objects in C++

When it comes to object-oriented programming, objects are the basic building blocks. Memory is taken up by objects, which contain data and methods or functions that operate on it. On...

3 minutes read.

Single dimension array

C++ Array An array is a collection of data (elements) of the same data types. The elements of an array are allocated in contiguous memory allocation. Elements of the array are accessed through...

1 minute read.

Hashing in C++

Before understanding hashing, we need to know what the use of hashing is. Let us consider an example of a library which consists of many books.Having many books, searching for...

6 minutes read.

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.

C++ Structs

We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of...

6 minutes read.