In C#, the break
statement is used to exit a loop or a switch statement prematurely. It is commonly used to terminate the execution of a loop when a specific condition is met or to exit a switch statement once a matching case is found.
The break
statement can be used with the following constructs:
break
in a loop:
while (condition) { // Code... if (someCondition) { break; // Exit the loop } // Code... }
for (int i = 0; i < count; i++) { // Code... if (someCondition) { break; // Exit the loop } // Code... }
2. break
in a switch statement:
switch (variable) { case value1: // Code... break; case value2: // Code... break; // Other cases... default: // Code... break; }
In both cases, when the break
statement is encountered, the execution of the loop or the switch statement is immediately terminated, and the control flow continues with the statement following the loop or the switch.
It’s important to note that break
statements can only be used within loops or switch statements. If you try to use a break
statement outside of these constructs, it will result in a compilation error.
C# Break Statement with Inner Loop:
In C#, the break
statement can be used to exit an inner loop while still staying within an outer loop. This is useful when you have nested loops and you want to terminate the inner loop based on a certain condition, while continuing with the outer loop.
Here’s an example that demonstrates the usage of break
with an inner loop:
for (int i = 0; i < 5; i++) { Console.WriteLine("Outer loop: " + i); for (int j = 0; j < 3; j++) { Console.WriteLine("Inner loop: " + j); if (j == 1) { break; // Exit the inner loop } } }
In this example, there is an outer loop that iterates from 0 to 4, and an inner loop that iterates from 0 to 2. The break
statement is used within the inner loop with the condition j == 1
. When j
becomes 1, the break
statement is executed, causing the inner loop to terminate. However, the control flow then goes back to the outer loop, and the next iteration of the outer loop continues.
The output of the above code will be:
Outer loop: 0 Inner loop: 0 Inner loop: 1 Outer loop: 1 Inner loop: 0 Inner loop: 1 Outer loop: 2 Inner loop: 0 Inner loop: 1 Outer loop: 3 Inner loop: 0 Inner loop: 1 Outer loop: 4 Inner loop: 0 Inner loop: 1
As you can see, when the inner loop breaks at j == 1
, it goes back to the outer loop and continues with the next iteration of the outer loop until it completes all iterations.