Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use a "do while" loop? [closed]

I've never understood why using a do while loops is necessary. I understand what they do, Which is to execute the code that the while loop contains without checking if the condition is true first.

But isn't the below code:

do{
    document.write("ok");
}
while(x == "10");

The exact same as:

document.write("ok");
while(x == "10"){
    document.write("ok");
}

Maybe I'm being very stupid and missing something obvious out but I don't see the benefit of using do while over my above example.

like image 584
Stanni Avatar asked Jun 09 '10 06:06

Stanni


People also ask

Why would you use a Do While loop?

A do-while loop is used where your loop should execute at least one time. For example, let's say you want to take an integer input from the user until the user has entered a positive number. In this case, we will use a do-while as we have to run the loop at-least once.

Why would you use a Do While loop over a while loop?

Because do while loops check the condition after the block is executed, the control structure is often also known as a post-test loop. Contrast with the while loop, which tests the condition before the code within the block is executed, the do-while loop is an exit-condition loop.


1 Answers

What about:

do{

   //.....
   // 100000 lines of code!
   //.....

} while(i%10);




Of course you will not write that:

//.....
// 100000 lines of code!
//.....

while(i%10){

   //.....
   // 100000 lines of code!
   //.....

} 



And you will then be forced to use a do-while loop
God Bless it!!

Edit:
Or you will use procedures..

like image 120
Betamoo Avatar answered Oct 18 '22 01:10

Betamoo