C++ break Statement

About C++ break statement:

 On this page we will discuss about break statement  which is used in C++.
The break statement is used to exit a loop or switch statement early. It can be used to terminate a loop early, before the loop condition is evaluated again.
break statement in c++

What is C++ break statement ?

In C++ language, the break statement works by exiting the innermost loop or switch statement that it is in. When the break statement is encountered, the program immediately exits the loop or switch statement and continues with the next statement after the loop or switch.

Syntax:

break;

The break statements are typically used when we are not sure about the number of iterations which will be used for a loop or when we want to terminate the loop based on some condition.

In C++, the break statement is used in three ways:

  • Whenever a break statement is encountered within a loop, then the loop is terminated early, before the loop condition is evaluated again and and program continues with the next statement after the loop.
  • The break statement can be used to exit a switch statement early.
  • It can also be used to exit a loop inside a switch statement.

Flowchart:

break statement in c++ flowchart

Example 1:

Run
#include<iostream> 
using namespace std;
int main()
{
    for (int i = 0; i < 10; i++) {
     if (i == 5) {
       break;
     }
     std::cout << i << std::endl;
     }

    return 0;
}

Output:

0 
1
2
3
4

Example 2:

Run
#include<iostream>
using namespace std;
int main()
{
    int x = 10;
    switch (x) {
    case 1:
      std::cout << "x is 1" << std::endl;
      break;
    case 2:
      std::cout << "x is 2" << std::endl;
      break;
    default:
      std::cout << "x is not 1 or 2" << std::endl;
    }

    return 0;
}

Output:

x is not 1 or 2

Example 3:

Run
#include<iostream>
using namespace std;
int main()
{
    for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
        if (i == 2 && j == 2 || i== 3 && j==3 || i==1 && j==0) {
      break;
    }
    std::cout << i << " " << j << std::endl;
  }
}
    return 0;
}

Output:

0 0
0 1
0 2
2 0
2 1

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription