Hello Readers,
Today, we will learn about the C++ break statement. In the previous article, we discussed about continue statement in C++, if you don’t know about it, you can check it here.
Also, if you know programming, & want to practice, you can check these coding problems.
The break statement terminates the execution of the loop or conditional statement in which it appears. Control flow is transferred to the statement that follows the statement’s end, if any.
Related: Practice C++ star pattern problems here
C++ break statement
Break statement in C++ is used to terminate a loop or switch statement. It interrupts the program’s current flow at the given condition. When it is the case of an inner loop, it only breaks the inner loop.
The syntax for break statement:
break;
Related: Inverted Right Triangle pattern in C++
Flowchart of Break statement in C++
How Does the C++ Break Statement Work?
The break statement always allows you to exit the loop before its termination condition is met. The break statement effectively terminates the loop’s execution.
Within the loop body is a condition on which you will set the break statement or for which you want that the loop get breaks; if that condition is met, the loop’s execution is terminated. When the if condition is not satisfied, it will proceed to the next iteration.
Example:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
cout<<i<<"\n";
}
return 0;
}
Output
1
2
3
4
Related: Top 6 IDEs in C++
Explanation:
When the control flow goes to the for loop, it executes the condition mentioned. Inside the loop, ‘i‘ is initialized with 1, which is less than 10, and the condition is true so that the loop will get executed. If condition is false for 1 so it will print 1 directly.
The above process goes for 2,3, and 4. But when ‘i‘ reaches 5, the for condition is true, but it will go inside the if statement, which says if ‘i‘ is equal to 5, then execute break.
After executing the break statement, the control flow comes out of the loop.
Conclusion
After reading this article on break statement in C++, you would have understood the basics of a break statement. Still, if you have any doubts, just comment below or email us at: cpptopics@techoutflow.com.
The next tutorial will be out soon. Till then, stay tuned.