C# – Break statement
In C#, the break statement is used to terminate a loop(for, if, while, etc.) or a switch statement on a certain condition. And after terminating the controls will pass to the statements that present after the break statement, if available. If the break statement exists in the nested loop, then it will terminate only those loops which contain the break statements.
Now we will see the usage of break statement:
- Simple Loop
- Nested Loop
- Infinite Loop
- Switch-Case statement
1. Simple Loop:
Here we will discuss the use of break statements in simple for loop. As shown in the below example the for loop is programmed to execute from 0 to 20 but the output of this example is “0 1 2 3 4 5 6”. Because here we break the loop when the value of x is equal to 7. If we do not use a break statement, then this loop prints 0….20 numbers.
0 1 2 3 4 5 6
2. Nested Loop:
We can also use the break statements in the nested loops. If you use a break statement in the innermost loop, then control will come out only from the innermost loop. Let us discuss the use of break statement in the nested loops with the help of an example:
## ## ## ##
In the above example, the inner loop is programmed to execute for 4 iterations, but when the value of y is greater than 2 the inner loop stops executing because we use a break statement to restrict the number of iteration of the inner loop to 2. However, the outer loop remains unaffected.
3. Infinite Loops:
We can also use the break statement in the infinite loop to terminate the execution of the infinite loop. Let us discuss the use of break statement in the infinite loops with the help of an example:
In the above example, the loop condition based on which the loop terminates is always true. So, the loop will execute an infinite number of times, or we can say never terminate. So, here we use the break statement to terminate the loop when the value of x is equal to 7
Hey GeeksforGeeks Hey GeeksforGeeks Hey GeeksforGeeks Hey GeeksforGeeks Hey GeeksforGeeks Hey GeeksforGeeks
4. Switch-case Statement:
As we know that the switch statement has a drawback, i.e. when the matching value is found it will execute all the statements until the end of the switch block. To avoid such type of problem we use break statement in every case. So that the break statement terminates the execution of the switch statement for nonmatching statements. As shown in the below example:
Select option(1, 2, 3): 2 You select group B