C sharp - break and continue in C#
Clear explanation of break and continue in C#, along with their syntax and examples.
break
Syntax:
break;
Used to exit a loop (for, while, do-while, foreach) or a switch block immediately.
Example – break in a for loop:
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
break; // Exit the loop when i is 3
}
Console.WriteLine(i);
}
}
}
continue in C#
Syntax:
continue;
Used to skip the rest of the current iteration and move to the next loop cycle.
Example – continue in a for loop:
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
continue; // Skip printing 3
}
Console.WriteLine(i);
}
}
}
| Statement | Meaning | Common Use Case |
|---|---|---|
break |
Exits the entire loop or switch | Stop a loop early based on a condition |
continue |
Skips current loop iteration, continues next | Skip specific values or conditions in a loop |