In this section we’re assuming you already familiar with either of these loops: for, do while, while or a statement like switch.
The break and continue keywords are used in loops to create statements:
-
When `break` statement is used in a loop, it will break that loop
(jump out) and the computer will continue to execute the instructions
after the loop.
Note: other than loops, we use the break keyword in switch statement as well.
Example:
using System;
namespace quickExample
{
public class Program
{
public static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i > 5)
{
break;
}
Console.Write(i + ", ");
}
Console.WriteLine("nDone!");
}
}
}
Output:
0, 1, 2, 3, 4, 5,
Done!
Here, the for loop supposed to loop through 10 elements. But because there’s a break statement that will be triggered (in the if statement) after the value of the i variable becomes 6, the loop breaks at this point and the instructions after the loop run. In this case the instruction is just a simple message to the screen.
-
When `continue` statement is used in a loop, it will stop the
execution of the current iteration and continues with the next
iteration.
Example:
using System;
namespace quickExample
{
public class Program
{
public static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i < 5)
{
continue;
}
Console.Write(i + ", ");
}
Console.WriteLine("nDone!");
}
}
}
Output:
5, 6, 7, 8, 9,
Done!
In this example, as long as the value of the i variable in the loop, is less than the value 5, the iteration will be skipped by calling the continue; statement and the next iteration starts. That’s why those numbers that were less than 5 didn’t send to the output stream.