
π§ When working with loops, we often use continue
and break
to control the flow of execution — but do you truly understand how they behave together? Here's a small but tricky C# challenge that demonstrates their impact clearly.
Take a look at this loop:
public static void Main()
{
int i = 0;
for (; i < 10; i++)
{
if (i % 4 == 1)
{
continue;
}
Console.WriteLine(i);
if (i % 6 == 0 && i > 0)
{
break;
}
}
}
π What Will Be Printed?
Let’s walk through the loop step-by-step and see what gets printed and why.
Loop Logic:
-
Skip printing i
if i % 4 == 1
(i.e., 1 or 5)
-
Print i
otherwise
-
If i > 0 && i % 6 == 0
, break the loop
π§ Iteration Breakdown:
i |
i % 4 == 1 |
continue ? |
Printed? |
i % 6 == 0 && i > 0 |
break ? |
0 |
false |
no |
β
0 |
false |
no |
1 |
true |
β
yes |
β |
— |
— |
2 |
false |
no |
β
2 |
false |
no |
3 |
false |
no |
β
3 |
false |
no |
4 |
false |
no |
β
4 |
false |
no |
5 |
true |
β
yes |
β |
— |
— |
6 |
false |
no |
β
6 |
β
true |
β
break |
β
Final Console Output:
0
2
3
4
6
π― What You Should Learn
This compact loop tests your ability to mentally trace control flow using continue
and break
. Here’s what you should take away:
π‘ Key Takeaways
-
continue
skips the rest of the loop body
-
break
exits the loop entirely
-
Order of execution matters
-
continue
comes before the print, so it prevents output.
-
break
comes after the print, so the current value is printed, then the loop ends.
-
Understand how loop variables evolve
π§ Why This Matters
Control structures like break
and continue
are foundational — and they show up everywhere: in filtering logic, processing pipelines, retries, state machines, and more. Misunderstanding them can easily lead to bugs, skipped logic, or infinite loops.
By mastering these tools, you gain better control over execution flow and a deeper intuition for writing clear and correct logic.