C# Break: Loop and Switch Control
In C#, the break keyword is commonly used in loop or switch statements to terminate the loop or exit the switch statement. When the break statement is executed, the program immediately exits the current loop or switch statement and continues executing the code after the loop or switch statement.
Here is an example of how to use the “break” keyword:
Using break in a for loop:
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
Using break in a while loop.
int i = 0;
while (i < 10)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
i++;
}
Use the break statement in a switch statement.
int day = 4;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
default:
Console.WriteLine("Other day");
break;
}
In the above example, the keyword “break” is used to terminate a loop or exit the execution of a switch statement when a certain condition is met.