In C++, a do-while loop is similar to a while loop, but with one key difference: the condition is checked after the code block is executed, ensuring that the loop will always run at least once, even if the condition is initially false.
Syntax:
do {
// Code to be executed
} while (condition);
condition: This is a boolean expression that will be evaluated after each iteration of the loop. If the condition is true, the loop will continue. If the condition is false, the loop will terminate.
Code Process:
- The code inside the do block is executed first.
- After executing the code, the condition is evaluated.
- If the condition is true, the loop runs again.
- If the condition is false, the loop stops.
Example:
#include <iostream>
using namespace std;
int main() {
int count = 1;
// do-while loop
do
{
cout << "Count is: " << count << endl;
count++; // Increment the counter
}
while (count <= 5);
return 0;
}
Output:
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Example: If we define count > 5 in the while loop then it will execute only one time.
#include <iostream>
using namespace std;
int main() {
int count = 1;
// do-while loop
do
{
cout << "Count is: " << count << endl;
count++; // Increment the counter
}
while (count > 5);
return 0;
}
Output:
Difference between Do while loop and while loop
A do-while loop guarantees that the loop will run at least once, regardless of whether the condition is true or false initially.
In a while loop, the condition is checked before the loop runs, so if the condition is false to begin with, the code inside the loop may never execute.