0
0
CppComparisonBeginner · 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++.

Aspectwhile loopdo while loop
Condition CheckBefore loop body runsAfter loop body runs
Minimum ExecutionsZero times if condition falseAt least once always
Use CaseWhen condition must be true to startWhen loop must run once before checking
Syntaxwhile(condition) { ... }do { ... } while(condition);
Common PitfallMay skip loop if condition false initiallyMay run loop body even if condition false initially
⚖️

Key Differences

The main difference between while and do while loops is when the condition is checked. In a while loop, the condition is evaluated before the loop body executes. This means if the condition is false at the start, the loop body will not run at all.

In contrast, a do while loop executes the loop body first and then checks the condition. This guarantees the loop body runs at least once, even if the condition is false initially.

Because of this, while loops are best when you want to run code only if a condition is true from the start. do while loops are useful when you want to run the loop body first and then decide if it should repeat, such as when prompting a user for input at least once.

⚖️

Code Comparison

Here is an example using a while loop to print numbers from 1 to 3.

cpp
#include <iostream>
int main() {
    int i = 1;
    while (i <= 3) {
        std::cout << i << " ";
        i++;
    }
    return 0;
}
Output
1 2 3
↔️

do while Equivalent

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

cpp
#include <iostream>
int main() {
    int i = 1;
    do {
        std::cout << i << " ";
        i++;
    } while (i <= 3);
    return 0;
}
Output
1 2 3
🎯

When to Use Which

Choose while when you want to check the condition before running the loop, ensuring the loop may not run if the condition is false initially. This is common when the loop depends on a condition that might not be true at the start.

Choose do while when you need the loop body to run at least once regardless of the condition, such as when you want to prompt a user for input and then repeat based on their response.

Key Takeaways

Use while to check the condition before running the loop body.
Use do while to run the loop body at least once before checking the condition.
while loops may not run if the condition is false initially.
do while loops always run once, even if the condition is false.
Pick the loop type based on whether you need the loop body to run before or after the condition check.