0
0
CsharpComparisonBeginner · 3 min read

While vs Do While in C#: Key Differences and Usage

In C#, a while loop checks its condition before running the loop body, so it may not run at all if the condition is false initially. A do while loop runs the loop body first and then checks the condition, guaranteeing the loop runs at least once.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of while and do while loops in C#.

Factorwhile Loopdo while Loop
Condition CheckBefore loop body runsAfter loop body runs
Minimum ExecutionsZero times if condition is falseAt least once always
Use CaseWhen you may skip loop if condition falseWhen loop must run once before condition check
Syntaxwhile(condition) { ... }do { ... } while(condition);
Common ScenarioReading input until validMenu shown at least once
⚖️

Key Differences

The main difference between while and do while loops in C# is when the condition is checked. The while loop tests the condition before executing the loop body, so if the condition is false at the start, the loop body will not run even once. This makes it useful when you want to run the loop only if a condition is true from the beginning.

On the other hand, the do while loop executes the loop body first and then checks the condition. This guarantees that the loop body runs at least once, regardless of the condition. This is helpful when you want to perform an action first and then decide if it should repeat.

Because of this difference, while loops are often used when the number of iterations is uncertain and might be zero, while do while loops are preferred when the loop must execute at least once, such as displaying a menu or prompting user input before checking if it should continue.

⚖️

Code Comparison

This example uses a while loop to print numbers from 1 to 3.

csharp
int count = 1;
while (count <= 3)
{
    Console.WriteLine($"Count is {count}");
    count++;
}
Output
Count is 1 Count is 2 Count is 3
↔️

do while Equivalent

The same task using a do while loop looks like this:

csharp
int count = 1;
do
{
    Console.WriteLine($"Count is {count}");
    count++;
} while (count <= 3);
Output
Count is 1 Count is 2 Count is 3
🎯

When to Use Which

Choose while loop when you want to check the condition first and possibly skip the loop entirely if the condition is false initially. This is common when the loop might not need to run at all.

Choose do while loop when you need the loop body to run at least once before checking the condition, such as showing a menu or prompting user input that must happen at least once.

Key Takeaways

Use while to check condition before running loop body; it may run zero times.
Use do while to run loop body first, ensuring it runs at least once.
while is good for conditional loops that might not run.
do while is ideal for loops that must execute before condition check.
Both loops can achieve the same results but differ in when they check the condition.