While vs Do While in C: Key Differences and Usage
while loop checks the 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, ensuring the loop runs at least once.Quick Comparison
Here is a quick side-by-side comparison of while and do while loops in C.
| Aspect | while loop | do while loop |
|---|---|---|
| Condition Check | Before loop body runs | After loop body runs |
| Minimum Executions | 0 times if condition false | At least 1 time always |
| Use Case | When condition must be true to start | When loop must run once regardless |
| Syntax | while(condition) { ... } | do { ... } while(condition); |
| Loop Body Execution Guarantee | No | Yes |
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 at all. This makes it useful when you want to repeat something 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, even if the condition is false initially. This is helpful when you want to perform an action first and then decide if it should repeat.
Both loops use similar syntax but differ in placement of the condition check. The while loop uses while(condition) { ... }, while the do while loop uses do { ... } while(condition); with a semicolon at the end.
Code Comparison
This example shows a while loop that prints numbers from 1 to 3.
#include <stdio.h> int main() { int i = 1; while (i <= 3) { printf("%d\n", i); i++; } return 0; }
Do While Equivalent
This example shows the same task done with a do while loop, printing numbers from 1 to 3.
#include <stdio.h> int main() { int i = 1; do { printf("%d\n", i); i++; } while (i <= 3); return 0; }
When to Use Which
Choose while when you want to check the condition before running the loop, such as when the loop might not need to run at all. Choose do while when you want the loop body to run at least once, like when you need to prompt a user for input and then check if they want to continue.
Key Takeaways
while to run loops only if the condition is true from the start.do while to run the loop body at least once regardless of the condition.while is checked before the loop body; in do while, it is checked after.while(condition) { } vs do { } while(condition);.