Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The do-while statement [duplicate]

Possible Duplicate:
When is a do-while appropriate?

Would someone mind telling me what the difference between these two statements are and when one should be used over the other?

var counterOne = -1;

do {
    counterOne++;
    document.write(counterOne);
} while(counterOne < 10);

Or:

var counterTwo = -1;

while(counterTwo < 10) {
    counterTwo++;
    document.write(counterTwo);
}

http://fiddle.jshell.net/Shaz/g6JS4/

At this moment in time I don't see the point of the do statement if it can just be done without specifying it inside the while statement.

like image 341
Shaz Avatar asked Apr 08 '11 18:04

Shaz


2 Answers

Do / While VS While is a matter of when the condition is checked.

A while loop checks the condition, then executes the loop. A Do/While executes the loop and then checks the conditions.

For example, if the counterTwo variable was 10 or greater, then do/while loop would execute once, while your normal while loop would not execute the loop.

like image 141
Tejs Avatar answered Sep 23 '22 06:09

Tejs


The do-while is guaranteed to run at least once. While the while loop may not run at all.

like image 45
Daniel A. White Avatar answered Sep 25 '22 06:09

Daniel A. White