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.
Its functionality is the same as the while loop, except that the condition in the do-while loop is evaluated after the execution of the statement instead of before, granting at least one execution of the statement even if the condition is never fulfilled.
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.
C++ Do while loop – Questions and Answers
Q 1: What is a do-while loop?
Ans: A loop that executes at least once.
Q 2: Is do-while entry or exit controlled?
Ans: Exit-controlled.
Q 3: Where is condition checked?
Ans: After loop body.
Q 4: Is semicolon required after while?
Ans: Yes.
Q 5: When to use do-while?
Ans: When code must run at least once.
C++ Do while loop – Objective Questions (MCQs)
Q1. What is the correct syntax of a do-while loop in C++?
Q2. When is the condition checked in a do-while loop?
Q3. What is the output of the following code?
int i = 1;
do {
cout << i << " ";
i++;
} while (i <= 3);
Q4. Which statement is true about the do-while loop?
Q5. What will be the output of this code?
int x = 6;
do {
cout << x << " ";
x++;
} while (x < 6);