Explain difference between while and do-while loop.

The syntax of while loop is

while(expression)
{
statement;
statement;
}


the syntax of do while loop is

do
{

statement;
statement;
}
while(expression);


From the above syntax it is clear that in while loop expression is tested first and then the body is executed.
If expression is evaluated to true it is executed otherwise not.


In do while loop, body is executed first and then the expression is tested. If test expression is evaluated to true then body of loop is again executed.

Thus it is clear that the body of do while loop gets executed at least once, where as, it is not necessary in while loop.

No comments:

Post a Comment