Curriculum
In C#, the break
keyword is used to terminate a loop or a switch statement and transfer control to the statement immediately following the loop or switch.
Here’s an example of using the break
keyword inside a for
loop:
for (int i = 0; i < 10; i++) { if (i == 5) { break; } Console.WriteLine(i); }
In this example, the for
loop will iterate from i=0
to i=9
. However, when i=5
, the break
statement is executed, and the loop terminates prematurely. Therefore, only the values of i
from 0
to 4
will be printed to the console.
Here’s an example of using the break
keyword inside a switch
statement:
int x = 2; switch (x) { case 1: Console.WriteLine("x is 1"); break; case 2: Console.WriteLine("x is 2"); break; default: Console.WriteLine("x is neither 1 nor 2"); break; }
In this example, the switch
statement evaluates the value of x
and executes the corresponding case statement. When x=2
, the second case statement is executed, and the break
statement is encountered, causing the switch statement to terminate. Therefore, the output of this program is “x is 2”.
The rules for using the break
keyword in C# are as follows:
break
statement can only be used inside a loop or a switch statement.break
statement is executed inside a loop, the loop immediately terminates, and the control flow resumes at the statement following the loop.break
statement is executed inside a switch statement, the switch statement immediately terminates, and the control flow resumes at the statement following the switch.In summary, the break
keyword is a useful tool for controlling the flow of execution in C# programs. By using the break
keyword in loops and switch statements, you can terminate the loop or switch prematurely and transfer control to the next statement in your program.