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:
| Parameter | Type | Description |
|---|---|---|
| while | Loop | Tests condition before running body. |
Ready-to-Run Code Example
Executable in CompilraRun 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
C# Generic List Collections Iteration Mechanics via Foreach
Master generic List<T> collection traversal in C# using foreach, understanding IEnumerable<T> enumerator state and read-only cursor safety.
C# Break and Continue Statements in Loops
Interrupt or skip loop iterations using break and continue in C#.
C# Pattern Matching Switch Statements and Expressions
Implement modern C# pattern matching switch expressions (=>) with relational ranges, logical combinators (and/or), and discard guards.
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.