Break Continue

C# Break

You have seen many places where break statement is used, like in switch expression or loop. In C# break statement is used to jump out of the for loop whenever some specific condition met. For example we are iterating in the loop and if looping variable reaches to some specific value then we want to jump out from the current loop. For example

Try it
for (int loop = 0; loop < 5; loop++)
{
    if (loop == 3)
    {
        break;
    }
    Console.WriteLine("Counter is : {0}", loop);
}
// Output 
Counter is : 0
Counter is : 1
Counter is : 2

C# Continue

C# also supports "continue" statement along with "break" statement. It generally used to skip particular iteration within the loop. While we are interating within the loop and we want to skip iteration when some specific condition met "continue" statement can be used.

Below example will skip the iteration where loop counter is 3. For example

Try it
for (int loop = 0; loop < 5; loop++)
{
    if (loop == 3)
    {
        continue;
    }
    Console.WriteLine("Counter is : {0}", loop);
	// Output 
	Counter is : 0
	Counter is : 1
	Counter is : 2
	Counter is : 4
}

In above example we have seen usage of break and continue statement in for loop. We will also see the usage of break and continue statement within while loop. It performs same as how it performs in for loop.

Break and Continue in While Loop

Try it - Break Example
int loop = 0;
while (loop < 5)
{
    Console.WriteLine("Counter is : {0}", loop);
    loop++;
    if (loop == 2)
    {
        break;
    }
}
//Output
Counter is : 0
Counter is : 1
Try it - Continue Example
int loop = 0;
while (loop < 5)
{
    if (loop == 2)
    {
        loop++;
        continue;
    }
    Console.WriteLine("Counter is : {0}", loop);
    loop++;
}
//Output
Counter is : 0
Counter is : 1
Counter is : 3
Counter is : 4

 

← Previous

Next →