BM Balmiki Mandal 20 Jul 2023 0 views 0 comments C# (C Sharp)

Using C# Break and Continue Statements

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.

Share:

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Understanding and Applying C# Delegates

What is a Delegate in C#? A delegate in C# is a type that defines a method signature. It can be used to pass...

BM Balmiki Mandal 20 Jul 2023
Understanding C# Threads and Multithreading

C# Threads and Multithreading Multithreading in C# is an important concept to learn when developing software...

BM Balmiki Mandal 20 Jul 2023
Event Programming in C#

What You Need to Know About C# Events C# is a powerful, object-oriented programming language developed by Mic...

BM Balmiki Mandal 20 Jul 2023