🔁 Break and Continue in C#
In C#, break
and continue
are loop control statements that let you alter the flow of loops.
These statements make your code more efficient and flexible.
📘 What is break
?
The break
statement terminates the nearest enclosing loop instantly when a specific condition is met.
📘 What is continue
?
The continue
statement skips the current iteration of the loop and moves directly to the next cycle.
💡 Example: Break and Continue
using System;
class Program
{
static void Main()
{
Console.WriteLine("Break Example:");
for (int i = 1; i <= 5; i++)
{
if (i == 3)
break;
Console.WriteLine("i = " + i);
}
Console.WriteLine("\nContinue Example:");
for (int i = 1; i <= 5; i++)
{
if (i == 3)
continue;
Console.WriteLine("i = " + i);
}
}
}
📝 Sample Output
Break Example:
i = 1
i = 2
Continue Example:
i = 1
i = 2
i = 4
i = 5
i = 1
i = 2
Continue Example:
i = 1
i = 2
i = 4
i = 5
🔍 Explanation
- Break: Loop stops completely when
i == 3
. - Continue: When
i == 3
, the current iteration is skipped. - These are useful in filtering, conditionally stopping, or skipping logic inside loops.
Post a Comment