C Mastering Loop Control: Understanding continue and break in C#

Mastering Loop Control: Understanding continue and break in C#

🧠 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

  1. continue skips the rest of the loop body

    • It immediately moves to the next iteration, bypassing any code below it.

  2. break exits the loop entirely

    • As soon as the condition is met, the loop stops — no more iterations.

  3. 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.

  4. Understand how loop variables evolve

    • Don’t forget the loop’s i++ still happens unless the loop is broken with break.


🧠 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.

Add comment