Break and continue in C# full Explanation
In C#, the `break` and `continue` statements are
control flow statements used within loops (such as `for`, `while`, and
`do-while`) to alter the normal execution of the loop. Here's a full
explanation of `break` and `continue` in C#:
1.
`break` Statement:
v The
`break` statement is used to exit the loop prematurely.
v When
encountered inside a loop, the `break` statement immediately terminates the
loop and the program execution continues with the next statement after the
loop.
v It
is commonly used when a certain condition is met, and you want to exit the loop
early.
v Example:
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break; // Exit the loop when i equals 5
}
Console.WriteLine(i);
}
In this
example, the loop will print numbers from 0 to 4, but when `i` becomes 5, the
`break` statement is encountered, and the loop is terminated.
2.
`continue` Statement:
v The
`continue` statement is used to skip the remaining code inside the loop for the
current iteration and move to the next iteration.
v When
encountered inside a loop, the `continue` statement jumps to the next iteration
of the loop without executing any further code within the loop block.
v It
is commonly used when you want to skip certain iterations based on a specific
condition.
v Example:
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0)
{
continue; // Skip even numbers
}
Console.WriteLine(i);
}
In this
example, the loop will print only odd numbers because when `i` is an even number,
the `continue` statement is encountered, and the loop moves to the next
iteration.
Both the `break` and `continue` statements provide
control over the flow of execution within loops, allowing you to customize the
behavior based on certain conditions. It is important to use these statements
judiciously to ensure the desired logic and avoid infinite loops or unexpected
behavior.
0 Comments