Sometimes you want to exit a loop early or skip certain steps. C# gives you keywords for this.
⏹️ break
Ends the loop immediately.
1
2
3
4
5
6
for (int i = 1; i <= 10; i++)
{
if (i == 5)
break;
Console.WriteLine(i); // Prints 1-4
}
⏭️ continue
Skips the rest of the loop’s body and starts the next iteration.
1
2
3
4
5
6
for (int i = 1; i <= 5; i++)
{
if (i == 3)
continue;
Console.WriteLine(i); // Prints 1, 2, 4, 5
}
⏪ return
Exits the current method (even if it’s inside a loop).
1
2
3
4
5
6
7
8
9
void PrintUntil(int max)
{
for (int i = 1; i <= 10; i++)
{
if (i > max)
return;
Console.WriteLine(i);
}
}
💡 Try It!
Write a loop that prints numbers 1-10, but skips even numbers.
1
2
3
4
5
6
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
continue;
Console.WriteLine(i);
}
Next: Methods and functions in C#!