C# Break/Continue
Controlling loop execution.
C# Break and Continue
Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
Examples
Break Example
Stops the loop when i is 4.
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
break;
}
Console.WriteLine(i);
}
}
}Continue Example
Skips printing 4.
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
continue;
}
Console.WriteLine(i);
}
}
}Break in While Loop
Using break in a while loop.
using System;
class Program
{
static void Main(string[] args)
{
int i = 0;
while (i < 10)
{
Console.WriteLine(i);
i++;
if (i == 4)
{
break;
}
}
}
}