Saturday 21 September 2013

Do while loop

Do While Statement
We have seen that there may be certain situations when the body of while loop does not execute even a single time. This occurs when the condition in while is false. In while loop, the condition is tested first and the statements in the body are executed only when this condition is true. If the condition is false, then the control goes directly to the statement after the close braces of the while loop. So we can say that in while structure, the loop can executed zero or more times. There may be situations where we may need that some task must be performed at least once.
For example, a computer program has a character stored from a-z. It gives to user five chances or tries to guess the character. In this case, the task of guessing the character must be performed at least once. To ensure that a block of statements is executed is as under:
do
{
            Statement(s);
}
While(condition);

Note: This do while loop will be executed as far as the condition is true. So it is better to use do while when you do not know when the condition will go false.

Note: The difference between the while loop and do while loop in a programming language is that while loop will execute zero or more times on the other hand the do while loop will execute one or more times.




No comments:

Post a Comment