Break and Continue Statement In C#

In our earlier post we learned about basics of loops in C#. break and continue statements are used to terminate execution of code inside the loop. Let's get a bit more detail about these two.







Break Statement


break statement is used to terminate the execution of the code. It can be used inside the loops or inside switch case. Whenever inside a loop, if break statement comes then the loop is terminated and program control reaches at the next statement following the loop. Consider the below example

for(int i=0; i < 50, i++)
{
    if(i == 3)
    {
        break;
    }
    Console.WriteLine(i);
}

//Output
//0
//1
//2

Shown above is an example of for-loop where break statement is used. As you can notice in the output, where the value of i reached 3 the loop terminated and didn't print any number further on.

You can see switch statement post to understand how break is used in there.

Continue Statement


continue statement is used only in loops and the only difference between break and continue is that continue doesn't terminates the loop. continue statement prevents the execution of code beneath it and makes the loop jump to next iteration. Consider the below example.


for(int i=0; i < 10; i++)
{
    if(i == 3)
    {
        continue;
    }
    Console.WriteLine(i);
}

//Output
//0
//1
//2
//4
//5
//6
//7
//8
//9

In the above example when the value of i reached 3 continue statement is executed and it made the loop to iterate to next statement. Because of continue, the condition statement of loop and iteration statement is executed and loop continued to work normally. So in easy words continue statement just skips the internal execution of loop.


Try yourself and find out various usages of these loops. Let us know if you any query or concerns. Happy Reading (refer full series here - C# Tutorial Index)





Comments

Popular posts from this blog

Create Android Apps - Getting Started

Kotlin Type Checking and Smart Cast with Examples