I know what do does, and how it cooperates with the while loop, but won\'t a while loop code be the same, whether or not the do is there?
The biggest difference between while and do-while statement is, whether it is executed at least one time or not.
while(false)
printf("print!");
with this statement, the program will never print the string. However,
do{
printf("print!");
}while(false);
with this statement, the program will print the string once.
But many people don't recommend to use do-while statement--because it can be substituted with while statement. It doesn't mean that do-while statement is critically harmful, but it is rarely used.
In fact, for loop is the most safe and recommended way because the programmer can handle the iteration number, loop conditions, and increasing variables easily. So if you don't have any specific reason that you have to use while loop, just use for loop.
Consider the following:
while(condition){
myFunction();
}
and
do{
myFunction();
}while(condition);
The second form executes myFunction()
at least once then checks the condition
! To do so with a while
loop you've to write:
myFunction();
while(condition){
myFunction();
}
Use do-while() construct when you have to get your task executed at least once even if condition fails. Use while() when you your task to be executed only on certain condition success.
if you write the "loop" like so (without the do
as in your question):
int i=0;
{
System.out.println(i++);
}while(i<10);
it will just print out 0
(nothing more), and not loop 10 times.. so no, the loop won't be the same if the do isnt there.
The difference is with "do-while" loop will be executed at least one time. With "while" loop with false condition the loop body will not be executed.