Do-while Loop in C++ | Topic 11 | VU Insider



The Scenario

There can be the scenario when while loop does not run even a single time. This can occur when the expression in while loop is false. In while loop, the condition is tested first and the statements are executed when the condition is true. So, we can say that the while loop can execute 0 ore more times.

DO-WHILE Loop in C++

There can be the situation when we have to execute the task at least once. C language provides this feature in Do-while structure. In Do-while loop, the loop is executed once before checking if the condition is true.

Syntax:
do {
statement1;
statement2;
...
}
while (condition); code-box


Example:
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5); code-box


Another example: To guess a character from a-z
char x;
do {
cout<<"Please enter a character from a-z : ";
cin>>x;
if(x=='a') {
cout<<"Congrats, your guess is correct.";
}
}
while (x!='a'); code-box

Post a Comment

Previous Post Next Post