Description
in c++
Explanation & Answer
The break statement is used with the conditional switch statement and with the do, for, and while loop statements.
In a switch statement, the break statement causes the program to execute the next statement outside the switch statement. Without a break statement, every statement from the matched case label to the end of the switch statement, including the default clause, is executed.
In loops, the break statement ends execution of the nearest enclosing do, for, or while statement. Control passes to the statement that follows the ended statement, if any.
Within nested statements, the break statement ends only the do, for, switch, or while statement that immediately encloses it. You can use a return or goto statement to transfer control from more deeply nested structures.
Example
The following code shows how to use the break statement in a for loop.
#include <iostream> using namespace std; int main() { // An example of a standard for loop for (int i = 1; i < 10; i++) { cout << i << '\n'; if (i == 4) break; } // An example of a range-based for loop int nums []{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int i : nums) { if (i == 4) { break; } cout << i << '\n'; } }