I understand how does a do while loop works, it first runs the code once then check the condition.
What is the purpose of a 'do while loop' and is there any real life examples?
Thank you
I understand how does a do while loop works, it first runs the code once then check the condition.
What is the purpose of a 'do while loop' and is there any real life examples?
Thank you
Basically the only difference between while and do-while is that while loops check the loop test condition before entering the loop and do-while loops check the loop test condition after the loop is executed, both effectively having the same result except that do-while guarantees at least one execution of the loop.
Do-while loops are sometimes useful if you want the code to output some sort of menu to a screen so that the menu is guaranteed to show once.
Example:
int data;
do
{
cout << "Enter 0 to quit: ";
cin >> data;
cout << endl << endl;
} while (data != 0);
You can accomplish this same thing using just a while loop also. The only difference is that you must initialize the variable to a value that would not prevent the while loop from being entered.
int data = 1;
while (data != 0)
{
cout << "Enter 0 to quit: ";
cin >> data;
cout << endl << endl;
}
You pretty much answer your own question in the first line. However, it's instructive to look at the alternatives in a language like Python, that doesn't have a do-while
loop. The main difference is that a while
loop checks its condition before executing the body, while a do-while
loop checks the condition after the body. Python's general syntax doesn't allow for the second, since there's no way (that I can really think of) to attach a line of code to the end of an indented block.
A typical example is verifying an input value, where you want to read the first value, verify it against some condition, then continue to ask for a new value if it fails the verification. In pseudo-Python, it might look like
do:
x = input("Enter yes or no")
while x not in ("yes", "no")
However, Python doesn't have any such construct, so you either repeat the input and use a while
loop:
x = input("Yes or no")
while x not in ("yes", "no"):
x = input("Yes or no")
or you write an "infinite" loop with an explicit if
statement to break out:
while True:
x = input("Yes or no")
if x in ("yes", "no"):
break
Real World Example,
Go to the bath room:
DO {
Check_Door_Lock();
} WHILE (WAIT_WHILE_DOOR_IS_LOCKED());
after the loop is done then the WAIT_WHILE_DOOR_IS_LOCKED() has returned a false value, so it isn't locked anymore, thus, the whole loop ends.