Break Statement in C# Language
The C# programming language, like many other languages, provides developers with a wide range of control flo
w statements to manipulate the execution of code. One such control flow statement is the “break” statement. In this post, we’ll explore the “break” statement in C# and provide examples to illustrate its usage.What is the Break Statement in C# Language?
The “break” statement in C# is used primarily in loop constructs to terminate the loop prematurely, providing a way to exit the loop’s block of code before it reaches its natural termination condition. This statement is particularly useful when you want to exit a loop based on a certain condition or criteria.
Syntax of the Break Statement in C# Language
The syntax of the “break” statement in C# is quite simple:
break;
The “break” statement is typically used within loops such as “for,” “while,” and “do-while” loops.
Example 1: Using Break in a For Loop
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
Console.WriteLine("Loop terminated at i = 5");
break; // Exit the loop when i is 5
}
Console.WriteLine("Current value of i: " + i);
}
In this example, the loop will be terminated when the value of i
becomes 5, and the program will output:
Current value of i: 1
Current value of i: 2
Current value of i: 3
Current value of i: 4
Loop terminated at i = 5
Example 2: Using Break in a While Loop
int number = 0;
while (number < 10)
{
if (number == 7)
{
Console.WriteLine("Loop terminated at number = 7");
break; // Exit the loop when number is 7
}
Console.WriteLine("Current value of number: " + number);
number++;
}
In this example, the loop will be terminated when the value of number
becomes 7, and the program will output:
Current value of number: 0
Current value of number: 1
Current value of number: 2
Current value of number: 3
Current value of number: 4
Current value of number: 5
Current value of number: 6
Loop terminated at number = 7
Example 3: Using Break in a Switch Statement
The “break” statement can also be used within a “switch” statement to exit the switch block.
int choice = 2;
switch (choice)
{
case 1:
Console.WriteLine("You chose option 1.");
break; // Exit the switch block
case 2:
Console.WriteLine("You chose option 2.");
break; // Exit the switch block
case 3:
Console.WriteLine("You chose option 3.");
break; // Exit the switch block
default:
Console.WriteLine("Invalid choice.");
break; // Exit the switch block
}
In this example, the “break” statement is used to exit the “switch” block immediately after a case is matched.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.