C# Break and Continue
Introduction to Break and Continue
In C#, the 'break' and 'continue' statements are used to alter the normal execution flow of loops and switch statements.
The 'break' statement immediately ends the closest enclosing loop or exits a switch case.
The 'continue' statement skips the remainder of the current loop iteration and proceeds directly to the next iteration.
Using Break in Loops
The 'break' statement is useful when you want to exit a loop as soon as a specific condition is satisfied, even if the loop has not yet completed all its iterations.
using System;
namespace BreakExample
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break; // exit the loop when i equals 5
}
Console.WriteLine($"i = {i}");
}
}
}
}
i = 0 i = 1 i = 2 i = 3 i = 4
Using Continue in Loops
The 'continue' statement is used when you want to skip over certain loop iterations without terminating the entire loop.
This is often helpful when you want to process only specific values and ignore others within the same loop.
using System;
namespace ContinueExample
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0)
{
continue; // skip even numbers
}
Console.WriteLine($"i = {i}");
}
}
}
}
i = 1 i = 3 i = 5 i = 7 i = 9
Break vs Continue
The 'break' statement terminates the entire loop immediately and transfers control to the first statement after the loop.
The 'continue' statement only skips the current iteration of the loop and execution continues with the next iteration.