While vs Do While in C#: Key Differences and Usage
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#.
| Factor | while Loop | do while Loop |
|---|---|---|
| Condition Check | Before loop body runs | After loop body runs |
| Minimum Executions | Zero times if condition is false | At least once always |
| Use Case | When you may skip loop if condition false | When loop must run once before condition check |
| Syntax | while(condition) { ... } | do { ... } while(condition); |
| Common Scenario | Reading input until valid | Menu 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.
int count = 1; while (count <= 3) { Console.WriteLine($"Count is {count}"); count++; }
do while Equivalent
The same task using a do while loop looks like this:
int count = 1; do { Console.WriteLine($"Count is {count}"); count++; } while (count <= 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
while to check condition before running loop body; it may run zero times.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.