C++ Break Statement


C++ Break Statement

In this tutorial, we will learn about the break statement in C++. We will cover the basics of using the break statement to exit loops and switch statements.


What is a Break Statement

A break statement is used to terminate the execution of a loop or switch statement. When a break statement is encountered, control is transferred to the statement immediately following the loop or switch.


Syntax

The syntax for the break statement in C++ is:

break;

The break statement can be used in for, while, do-while loops, and switch statements to exit the current loop or switch block prematurely.

Flowchart of Break Statement


Exiting a For Loop Early

  1. Declare an integer variable i.
  2. Use a for loop to iterate from 1 to 10.
  3. Inside the loop, use an if statement to check if i is equal to 5.
  4. If the condition is true, use a break statement to exit the loop.
  5. Print the value of i.

C++ Program

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

Output

1 2 3 4 


Exiting a While Loop Early

  1. Declare an integer variable i and initialize it to 1.
  2. Use a while loop to iterate while i is less than or equal to 10.
  3. Inside the loop, use an if statement to check if i is equal to 5.
  4. If the condition is true, use a break statement to exit the loop.
  5. Print the value of i.

C++ Program

#include <iostream>
using namespace std;
int main() {
    int i = 1;
    while (i <= 10) {
        if (i == 5) {
            break;
        }
        cout << i << " ";
        i++;
    }
    return 0;
}

Output

1 2 3 4 


Exiting a Switch Statement

  1. Declare an integer variable num and assign a value to it.
  2. Use a switch statement to check the value of num.
  3. Use a case statement for different values of num.
  4. Inside each case, use a break statement to exit the switch statement after the matching case block is executed.
  5. Print a message indicating the value of num.

C++ Program

#include <iostream>
using namespace std;
int main() {
    int num = 2;
    switch (num) {
        case 1:
            cout << "Number is 1";
            break;
        case 2:
            cout << "Number is 2";
            break;
        case 3:
            cout << "Number is 3";
            break;
        default:
            cout << "Number is not 1, 2, or 3";
    }
    return 0;
}

Output

Number is 2