C#:C# Break and Continue Statements in Loops
C#•Loop Control

C# Break and Continue Statements in Loops

break terminates loop execution immediately; continue skips to the next iteration.

Syntax

if (condition) break; if (condition) continue;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
breakKeywordExits loop completely.
continueKeywordSkips remainder of current iteration.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C# locally:

using System;

public class Program {
    public static void Main() {
        int[] portCodes = {80, 443, -1, 8080, 9999, 3000};

        Console.WriteLine("Scanning ports:");
        foreach (int port in portCodes) {
            if (port < 0) {
                Console.WriteLine($"  [SKIP] Invalid port: {port}");
                continue;
            }
            if (port == 9999) {
                Console.WriteLine("  [STOP] Sentinel port 9999 hit. Halting scan.");
                break;
            }
            Console.WriteLine($"  [OPEN] Active port: {port}");
        }
    }
}
Expected Output:
Scanning ports:
  [OPEN] Active port: 80
  [OPEN] Active port: 443
  [SKIP] Invalid port: -1
  [OPEN] Active port: 8080
  [STOP] Sentinel port 9999 hit. Halting scan.

How It Works: Step-by-Step

  • Lines 9-12: continue skips -1.
  • Lines 13-16: break halts scan upon 9999.

Key Concepts

  • continue skips to the next item in foreach/for.
  • break terminates only the innermost loop.

Common Mistake: Using continue before incrementing in while loop

Skipping the increment in while loops causes an infinite loop.

❌ Incorrect
while (i < 5) { if (i == 2) continue; i++; }
✅ Correct
while (i < 5) { if (i == 2) { i++; continue; } i++; }

Related C# Tutorials & Compiler

Run and test C# on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C# Online Compiler