break and continue
Learn to exit a loop with break and skip with continue.
break and continue
break exits the loop entirely; continue skips the current step and moves to the next. Both change the control flow inside a loop.
For example, in a search loop, breaking out when found is sensible. To skip even numbers you write if (n % 2 == 0) continue;; this step is skipped and the loop continues with the next element.
Smart break usage
break and continue make a loop more efficient. For example, breaking once you find a target in a list skips the remaining elements, which speeds up large lists.
However, deep nesting of break and continue hurts readability. When possible, move the condition into the loop header or use a helper method for clarity. Reach for them only when really needed.
Exercise Find the first match with break
Use a for loop from 0 to 9. When i reaches 4, exit the loop with if (i == 4) break;. Otherwise print i with Console.WriteLine. The output should be 0, 1, 2, 3 (4 is not printed).
Show example solution
Write for (int i = 0; i < 10; i++) { if (i == 4) break; Console.WriteLine(i); }
Example solution:
using System;
class Program
{
static void Main()
{
for (int i = 0; i < 10; i++)
{
if (i == 4) break;
Console.WriteLine(i);
}
}
}
Test yourself
-
Write the loop exit
for (int i = 0; i < 100; i++) { if (i == 5) ____; Console.WriteLine(i); }Show answer
for (int i = 0; i < 100; i++) { if (i == 5) break; Console.WriteLine(i); } -
Match each statement to its effect
- break
- Exits the loop
- continue
- Skips the step
- return
- Exits the method
- throw
- Raises an error
-
What does the break statement do?
while (true) { if (done) break; }- Skips the step, moves to next
- Exits the method
- Exits the loop entirely
- Raises an error
Show answer
Exits the loop entirely — Correct. break exits the loop entirely; continue only skips the current step.