Monday 18 June 2018

loop break vs continue in c#

As we all know what a loop does, most of us are also familiar with the usage of break and continue statement within loops in c#. The problem is with the new comers who struggles in understanding the basic purposes and objectives of these two statements. I personally like c# and others like c# just because their meaningful coding conventions, we all know what break means as well as continue. As their name implies, they works in the same manner. A simple demonstration will help to clear doubts of any freshers about them.

break statement:
Break statements finishes the execution of a look at a specific time, with a specific condition within the body of a loop. The looping structure ends with a break statement and the control moves to the code after the loop. So in the below code, when the if condition comes true, break statement executes which breaks the loop and the control moves down to the string initialization statement.

for (int i = 0; i <= 5; i++)
{
  if (i == 4)
      break;
}
string str = "Some string";

continue statement:
Continue statement enables the looping structure to continue its execution, it moves the control back to the main, head of the loop without executing the code written after continue statement. The following code will not run the statement of string initialization when the if condition becomes true and the control will transfer back to the head of for loop.

for (int i = 0; i <= 5; i++)
{
  if (i == 4)
      continue;
 string str = "Some string";
}

Note: both the statements i.e. break and continue will always be used within the body of a loop, you are not allowed to use them outside the body of the loop. You can use them with any type of loop as well.

No comments:

Post a Comment