C#:C# While and Do-While Loops with Examples
C#•Loops

C# While and Do-While Loops with Examples

Use while loops when the number of cycles depends on external conditions or queues.

Syntax

while (condition) {} do {} while (condition);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
whileLoopTests condition before running body.

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 countdown = 3;
        Console.WriteLine("--- Countdown ---");
        while (countdown > 0) {
            Console.WriteLine($"T-minus {countdown}...");
            countdown--;
        }
        Console.WriteLine("Liftoff! 🚀\n");

        int attempts = 0;
        do {
            attempts++;
            Console.WriteLine($"Execution count (runs at least once): {attempts}");
        } while (attempts < 1);
    }
}
Expected Output:
--- Countdown ---
T-minus 3...
T-minus 2...
T-minus 1...
Liftoff! 🚀

Execution count (runs at least once): 1

How It Works: Step-by-Step

  • Lines 6-9: while loop counts down from 3 to 0.
  • Lines 13-16: do-while executes block once before evaluating condition.

Key Concepts

  • while checks condition first; if false initially, it never executes.
  • do-while executes the body at least once.

Common Mistake: Missing counter decrement leading to infinite loop

Failing to mutate the condition variable freezes the thread.

❌ Incorrect
while (c > 0) { Console.WriteLine(c); } // Infinite loop!
✅ Correct
while (c > 0) { Console.WriteLine(c); c--; }

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