In this lesson, you will learn about the jump statement, in particular, the break Statement in C++, with an example to understand the topic.
Jump statements, then unconditionally transfer program control within a function. Jumping statements are a type of control that moves program execution control from one place to another. The C++ language defines the jump statements as break, continue, and goto.
In C++, you can halt the execution of a loop and transfer control to a statement that comes after the loop by inserting a break
statement.
Basic Syntax
break;
The while loop is used in the program below to output the value of the number after each iteration. Take note of the code here:
if (number == 13), then break;
The above statement indicates that the break statement ends the loop when the number equals 13. Therefore, values less than or equal to 13 are excluded from the output.
Example
//Program prints 15 to 8 integers #include <iostream> using namespace std; int main() { int number = 20; while (number >= 1) { if (number == 13) { break; } cout << number << " "; number--; } return 0; }
Output
20 19 18 17 16 15 14
This concludes the C++ break Statement lesson. The next lesson will teach about the continue Statement in C++.