it's useful for repeating an action until it's correct
String input;
...
do
{
input = getInput();
} while(isValid(input));
to do that with another loop, you'd have to write input = getInput();
twice
Question
I didn't find any practical use of do-while loop. As a studied we don't have control over the do-while loop when it executes for the first time and everything which can be done with do-while loop, can be don with while or for loop (assuming).
My Question is: Is there any situation where we use a do-while loop, or any particular situation where it gives more reliable results as compared to for and while loops?
Solution
it's useful for repeating an action until it's correct
String input;
...
do
{
input = getInput();
} while(isValid(input));
to do that with another loop, you'd have to write input = getInput();
twice
OTHER TIPS
do
/while
is precisely suitable when you always want to execute at least once, but you want to check whether or not to keep going at the end of the loop instead of at the start.
You can easily emulate it with a while loop, but sometimes the code becomes less clear that way. All three loop types can be emulated with each other, with more or less mess - but as all three are available, you should just pick the most appropriate loop for the job in hand.
I personally use both while
loops and do
/while
loops less often than for
loops, but sometimes a do
/while
is the most readable option.
Might as well say "I didn't find any practical use of for loop...everything which can be done with for loop, can be don with while loop (assuming)".
Technically you can replace any loop with literally any other loop given enough finangling with the loop guards and such. Some loops are just nicer to read than others.
do-while
is primarily "better" if you want to perform an action at least once, e.g. asking for input, or getting some random value until it fits into some constraint. You can do such an action by performing the action once outside a "regular" loop and looping from there, but it's just neater to use do-while
.
Do-while has generally better performance characteristics if the loop body must execute at least once. If you reformulate a do-while into a while/for, you add an extra evaluation of the loop exit condition.
Also, do-while(false) is usable as a structured alternative for deeply nested if conditions:
do {
if (!condition1)
break;
if (!condition2)
break;
if (!conditionN)
break;
// do something
} while (false);
instead of:
if (condition1) {
if (condition2) {
if (conditionN) {
// do something
}
}
}