C# Break and Continue
Break is a statement that leaves a loop at once. Continue is a statement that skips the rest of the current pass.
Leaving early
The loop would print up to 9 without break. The break at 3 ends it after 2.
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 3)
{
break;
}
Console.WriteLine(i);
}
}
}Skipping one pass
The pass for 3 uses continue. That pass prints nothing and the loop carries on.
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
if (i == 3)
{
continue;
}
Console.WriteLine(i);
}
}
}The first multiple
The loop tests each number in turn. The first number divisible by 7 prints, and break stops the search.
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 100; i++)
{
if (i % 7 == 0)
{
Console.WriteLine(i);
break;
}
}
}
}Example
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 8)
{
break;
}
if (i == 4)
{
continue;
}
Console.WriteLine(i);
}
}
}Key points
- Use break to leave a loop early.
- Use continue to skip the rest of the current pass.
- Continue still lets the next pass run.
- Break and continue both work inside for and while loops.
In this example, i counts up from 1. The first passes print 1, 2, and 3. The pass for 4 uses continue, so nothing prints. The next passes print 5, 6, and 7. At 8 the break runs and the loop ends.
Note
Break also ends a case in a switch statement.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C# Compiler
Exercise
What does continue do inside a loop?