Using C# Break and Continue Statements

20 Jul 2023 Balmiki Mandal 0 C# (C Sharp)

C# Break and Continue Statements

In C#, the break and continue statements are used to alter the flow of a loop. A break statement causes the loop to end immediately, while a continue statement causes the current iteration of the loop to end and the next to begin.

Break Statement

The break statement immediately ends the loop in which it appears. The break statement is typically used for terminating a loop when a certain condition is met. For example, the following code uses a break statement to exit the loop when the counter reaches 5:

for (int i = 0; i < 10; i++)
{
    if (i == 5)
        break;
    // Loop continues...
}

In this case, the loop will end right after the i variable is incremented to 5. All of the remaining iterations of the loop will be skipped.

Continue Statement

The continue statement causes the current iteration of the loop to end promptly and the next one to begin. In the following example, the continue statement causes the code in the loop to be skipped whenever i is 3 (note that the loop still continues even after the continue statement):

for (int i = 0; i < 10; i++)
{
    if (i == 3)
        continue;
    // Loop continues...
}

Sometimes, a break statement can also be replaced with a continue statement. For instance, in the previous example, the break statement could be swapped for a continue statement and the code would still work as expected.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.