break statement in programming is used to come out of the loop or switch statements. It is a jump statement that breaks the control flow of the program and transfers the execution control after the loop.
The use of break statements in nested loops terminates the inner loop and the control is transferred to the outer loop.
break statement Flowchart:
Syntax of break statement in C#:
1 2 | //break syntax break; |
Example C# break Statement
Use of break statement in a single loop in C#.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | using System; public class BreakStatement { public static void Main(string[] args) { for (int i = 1; i <= 10; i++) { if (i == 6) { //stops loop at 6th iteration break; } Console.WriteLine("Value of i: {0}", i); } } } |
Output:
1 2 3 4 5 | Value of i: 1 Value of i: 2 Value of i: 3 Value of i: 4 Value of i: 5 |
Example: C# break statement with the nested loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | using System; public class BreakNested { public static void Main(string[] args) { for (int i = 1; i <= 2; i++) { for (int j = 1; j <= 2; j++) { // for i = 1 and j = 2 is skipped in the output if (i == 1 && j == 2) break; Console.WriteLine("i: {0}, j: {1}", i, j); } } } } |
Output:
1 2 3 | i: 1, j: 1 i: 2, j: 1 i: 2, j: 2 |
As you can see in the output that i = 1
and j = 2
is skipped. This is because the break statement breaks the inner loop for i = 1
and j = 2
and transfer the control to the outer loop and the rest iteration continues until the loop condition is satisfied.