Break and continue is a very basic concept of any programming language, and I think it is supported by almost all popular languages e.g. C++, C#, Java, JavaScript, etc. I know that most of us know about it very well, but for fresher guys, its a little bit confusing. So, I am explaining here so that even freshers can understand and use it easily.
Break (breaks the loop/switch)
Break statement is used to terminate the current loop iteration or terminate the switch statement in which it appears.
Break statement can be used in the following scenarios:
- for loop (For loop & nested for loop and Parallel.for)
- foreach loop (foreach loop & nested foreach loop and Parallel. foreach)
- While (while loop & nested while loop)
- Do while (do while loop and nested while loop)
- Switch case (Switch cases and nested switch cases)
Continue (skip the execution of current iteration)
The continue statement is not the same as break statement. Break statement breaks the loop/switch whereas continue skips the execution of the current iteration only and it does not break the loop/switch i.e. it passes the control to the next iteration of the enclosing while loop, do while loop, for loop or for each statement in which it appears.
Let’s understand the difference via some examples:
List<int> EvenNumberList = new List<int>();
List<int> OddNumberList = new List<int>();
List<int> PrimeNumberList = new List<int>();
for (int i = 1; i <= 200; i++)
{
if (i > 100)
break; //I have to check for numbers less than 100
if (i % 2 == 0)
{
EvenNumberList.Add(i);
continue; //if a number is even then it cannot be odd or prime number so we can skip the current iteration.
}
else
{
OddNumberList.Add(i);
if (IsPrimeNumber(i))
{
PrimeNumberList.Add(i);
}
}
}
In the above example, I am checking if a number is greater than 100, then break the loop. No code for the loop will be executed after that.
If a number is even, then it cannot be an odd or prime number, so we can skip the current iteration.
We can break multiple for or for each loop using break,
//We can break multiple for /for each loop using break
bool BreakAllLoops = false;
for (int i = 0; i < 10; i++)
{
//do something
if (BreakAllLoops)
break;
for (int j = 0; j < 10; j++)
{
//do something
if (BreakAllLoops)
break;
for (int k = 0; k < 10; k++)
{
//do something
if (k == 5)
{
break;
}
}
}
}
Break statement in foreach, while, do while, Parallel.for, Parallel. Foreach
#region foreach loop break statement
foreach (var item in collection)
{
//do something
break;
}
#endregion
#region while loop break statement
while (true)
{
break;
}
#endregion
#region Do while break statement
do
{
break;
} while (true);
#endregion
#region Switch case break statement
int i = 10;
switch (i)
{
case 1:
//do someting;
i = 1;
break;
default:
i = 1;
break;
}
#endregion
#region Parallel.for break statement
Parallel.for(int m = 0; m < 10; m++)
{
break;
}
#endregion
#region Parallel.foreach break statement
Parallel.foreach(var item in collection)
{
break;
}
#endregion