1. Introduction
In C++ programming, while and do-while loops are used for executing a block of code repeatedly. While they are similar in many ways, they have a key difference in how they evaluate their condition and when they begin executing the loop body.
2. Key Points
1. A while loop checks its condition before executing the loop body.
2. A do-while loop executes its loop body at least once before checking the condition.
3. In a while loop, the loop body may not execute at all if the condition is false initially.
4. In a do-while loop, the loop body always executes at least once, regardless of the initial condition.
3. Differences
while Loop | do-while Loop |
---|---|
Condition checked before loop body execution. | Loop body executed once before condition check. |
May not execute if condition is false initially. | Guaranteed to execute at least once. |
4. Example
#include <iostream>
using namespace std;
int main() {
int count = 5;
// while loop example
cout << "while loop output: ";
while (count < 5) {
cout << count << " ";
count++;
}
cout << endl;
// do-while loop example
cout << "do-while loop output: ";
count = 5;
do {
cout << count << " ";
count++;
} while (count < 5);
cout << endl;
return 0;
}
Output:
while loop output: do-while loop output: 5
Explanation:
1. In the while loop example, since count is not less than 5, the loop body does not execute.
2. In the do-while loop example, the loop body executes once before the condition count < 5 is checked.
5. When to use?
- Use a while loop when you want the loop to execute only if the condition is true from the start.
- Use a do-while loop when you need to ensure that the loop body is executed at least once, such as in menus or user input validation.
Related C++/CPP Posts:
Difference Between Struct and Class in C++
Difference Between Pointer and Reference in C++
Difference Between null and nullptr in C++
Difference Between Array and Vector in C++
Difference Between const and constexpr in C++
Difference Between List and Vector in C++
Difference Between Function Overloading and Operator Overloading in C++
Difference Between Array and List in C++
Difference Between a While Loop and a Do-While Loop in C++
Difference Between new and malloc C++
Virtual Function vs Pure Virtual Function in C++
Compile Time Polymorphism vs Runtime Polymorphism in C++
Difference Between Shallow Copy and Deep Copy in C++
Comments
Post a Comment
Leave Comment