C++ break Statement

Hi everyone, inside this article we will see about C++ break Statement.

The “break” statement in C++ is used to terminate a loop early or exit a switch statement. When a “break” statement is encountered inside a loop or switch, the control is immediately transferred out of the loop or switch to the next statement following the loop or switch.

Syntax & Explanation

It is defined using the following syntax:

jump-statement;      
break;  

Here, a pictorial representation of break statement:

A Basic Program

Here’s a simple program in C++ that demonstrates the use of a break statement:

#include <iostream>
using namespace std;

int main()
{
    for (int i = 1; i <= 10; i++)
    {
        if (i == 5)
        {
            break;
        }
        cout << i << "\n";
    }
    return 0;
}

The output of this program will be:

1
2
3
4

C++ Break Statement with Inner Loop

The C++ break statement breaks inner loop only if you use break statement inside the inner loop.

A basic program for it:

#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";
        }
    }
    return 0;
}

The output of this program will be:

1 1
1 2
1 3
2 1
3 1
3 2
3 3

We hope this article helped you to understand about C++ break Statement in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.