C# - Continue
C# - The continue Statement
Section titled “C# - The continue Statement”Introduction to the continue Statement
Section titled “Introduction to the continue Statement”The continue statement in C# provides a way to immediately stop the current iteration of a loop and proceed to the next one. Unlike the break statement, which terminates the entire loop, continue only skips the remaining code within the current iteration.
Its behavior depends on the type of loop:
- In a
forloop, it jumps to the loop’s increment expression (i++). - In a
whileordo...whileloop, it jumps to the loop’s condition check.
Syntax
Section titled “Syntax”The syntax for a continue statement is simple:
continue;Flow Diagram
Section titled “Flow Diagram”You can visualize the flow of a loop with a continue statement as follows:
( Start Loop ) | v +---------------+ | Loop Condition|----(false)---->( End Loop ) +---------------+ | (true) | v+---------------------------------+| Loop Body Code #1 |+---------------------------------+ | v +-----------------+ | if (condition) |----(true)----> (Jump to next iteration) +-----------------+ (bypassing code below) | (false) | v+---------------------------------+| Loop Body Code #2 |+---------------------------------+ | v (Jump to next iteration)Using continue in a for Loop
Section titled “Using continue in a for Loop”A common use case is to process only items that meet certain criteria. In this example, we use continue to skip even numbers and print only the odd ones.
// Goal: Print all odd numbers from 1 to 10.
for (int i = 1; i <= 10; i++){ // If the number is even, skip the rest of this iteration. if (i % 2 == 0) { continue; // Proceed to the next value of i. }
// This line is only reached for odd numbers. Console.WriteLine($"Odd number: {i}");}
Console.WriteLine("Loop completed.");Output
Section titled “Output”Odd number: 1Odd number: 3Odd number: 5Odd number: 7Odd number: 9Loop completed.Using continue in a while Loop
Section titled “Using continue in a while Loop”When using continue in a while or do...while loop, it’s crucial to ensure the loop’s control variable is updated before the continue statement to avoid an infinite loop.
// Goal: Print numbers from 10 to 19, but skip 15.int a = 10;
while (a < 20){ if (a == 15) { // IMPORTANT: Increment 'a' *before* continuing. // Otherwise, 'a' would always be 15, and the loop would never end. a++; continue; }
Console.WriteLine($"Value of a: {a}"); a++;}Output
Section titled “Output”Value of a: 10Value of a: 11Value of a: 12Value of a: 13Value of a: 14Value of a: 16Value of a: 17Value of a: 18Value of a: 19Best Practices and Common Pitfalls
Section titled “Best Practices and Common Pitfalls”- Improving Readability:
continuecan sometimes make code cleaner than a deeply nestedifstatement. If the condition for skipping is simple,continueat the top of a loop can flatten the logic. - The Infinite Loop Trap: The most common error is creating an infinite loop. In
whileanddo-whileloops, always make sure that the variable controlling the loop’s exit condition is modified before you callcontinue. foreachLoops:continueworks seamlessly withforeachloops, making it an excellent tool for filtering collections during iteration.
Practical Example: Processing User Input
Section titled “Practical Example: Processing User Input”var inputs = new List<string> { "apple", "", "banana", "-1", "cherry" };var validFruits = new List<string>();
foreach (var input in inputs){ // Skip empty or invalid entries if (string.IsNullOrEmpty(input) || input == "-1") { Console.WriteLine($"Skipping invalid input: '{input}'"); continue; }
Console.WriteLine($"Processing valid fruit: {input}"); validFruits.Add(input.ToUpper());}
Console.WriteLine($"\nValid fruits processed: {string.Join(", ", validFruits)}");Output
Section titled “Output”Processing valid fruit: appleSkipping invalid input: ''Processing valid fruit: bananaSkipping invalid input: '-1'Processing valid fruit: cherry
Valid fruits processed: APPLE, BANANA, CHERRY