How to write C break statement?
IMP Never forget ; just after the break keyword.
Do you know the output of..?
Why break ..?
- Break is important, it provides extra facility in loop controlling.
- At desire condition break used to terminate the current loop.
- By using break, we can save time in program execution.
How break statement works in C programming
As you know the break statement is a loop control statement and it’s used in termination of loop. In loop, when a break statement is encountered, the loop iterations stop there immediately and control returns to the first statement just after the loop.
When to use break statement
We can use break statement in various situations but basically we use in such situation where we are not sure about the number of iterations in loop but we want to terminate the loop based on some conditions.
What is output...?
Where to use break statement
In C programming break statement can be used in 4 different below listed scenario.
- In switch statement
- In simple loop statement
- In nested loop statement
- In infinite loop statement
1. break; in switch statement
Output
Explanation
In above program, we know case 1 is true hence control will execute scope of case 1 and it prints You are Pass, there is a break; statement just after the printf() function, this break statement will terminate the switch case and the control will not check case 2 and default case.
Imp: If you remove the all break; from above program then what will be the output
Output
You are Pass
Result under process
Invalid User
2. break; in simple loop statement
Below we are going to list examples to understand how we can use break; in all simple loops.
break; in for loop
Output
→ break; after printf statement
Output
→ break; statement without condition.
Output
break; in while loop
Output
Note: Just like for and while loop we can use break; statement in do while loop.
3. break; in nested loop statement
Output
In above example you can see how nicely we can control nested loop using break; keyword for desired result. If we use break; in inner loop then it terminate only inner loop process.
4. break; in infinite loop statement
In below example, you can see how we are going to make infinite loop useful by using break statement.
Output
2 3 4 5 6 7 8 9 10 11 12 13 14 15
What is C Language?