Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Saturday, August 6, 2016

What is the purpose of a do-while loop?

What is the purpose of a do-while loop?


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?

Answer by yiabiten for What is the purpose of a do-while 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();  }  

Answer by Iurii Polishchuk for What is the purpose of a do-while loop?


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.

Answer by Subler for What is the purpose of a do-while loop?


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.

Answer by jungyh0218 for What is the purpose of a do-while loop?


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.

Answer by Ranjan Kumar for What is the purpose of a do-while loop?


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.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.