0
0
C++programming~5 mins

Break statement in C++

Choose your learning style9 modes available
Introduction

The break statement stops a loop or switch case early. It helps you exit when you found what you want or need to stop.

When searching for a specific item in a list and you want to stop once found.
When you want to exit a loop if a certain condition happens.
When you want to stop checking more cases in a switch statement after one matches.
When you want to avoid unnecessary work after a goal is reached.
Syntax
C++
break;

The break statement is used alone with a semicolon.

It works inside loops (for, while, do-while) and switch statements.

Examples
This loop prints numbers from 0 to 4. When i becomes 5, break stops the loop.
C++
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;
    }
    std::cout << i << " ";
}
Each case ends with break to stop checking other cases after a match.
C++
switch (day) {
    case 1:
        std::cout << "Monday";
        break;
    case 2:
        std::cout << "Tuesday";
        break;
    default:
        std::cout << "Other day";
        break;
}
Sample Program

This program prints numbers from 1 to 6. When it reaches 7, it prints a message and stops the loop using break.

C++
#include <iostream>

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 7) {
            std::cout << "Found 7, stopping loop.\n";
            break;
        }
        std::cout << i << " ";
    }
    return 0;
}
OutputSuccess
Important Notes

Break only stops the innermost loop or switch it is in.

Using break can make your code faster by avoiding extra work.

Summary

The break statement stops loops or switch cases early.

Use break to exit when a condition is met.

It helps make your program efficient and clear.