Do While Loop
When the loop is constructed using the while loop, the condition in the loop will be checked first & then the control will go inside the loop. But sometimes we want to execute the loop & then want to check the condition. In such case , do while loop is used.
The do while loop will be executed whether or not the condition in the loop is true at least for one time.
while (loop condition);
There is a minor different between the working of do while loops. This different is the place where the condition is tested. The while tested the condition before executing any of the statement with in the while loop.
As against this, the do while tests the condition after having executed the statement with the loop.
That means do while would execute its statement at least once even if the condition fails for the first time. The while, on the other hand will not execute its statement if the condition fails for the first time.
Summary of Do-While
- In Do-While loop, the condition is tested after executing the body of the loop once.
- In do-while, the body of the loop is executed at least once.
- It is exit control loop statement.
Compare while & do-while loop
|While loop||Do While loop|
|While loop checks the condition at the beginning of loop.||Do while loop checks the condition at the end of the loop.|
|While loop execution is more accurate as compare to do while loop.||Do while loop is not as accurate as while loop.|
|The false condition can be run once also.||It can run false condition once because to the condition is checked at the end of loop.|
|The syntax of while is as follows:
|The syntax of do while is as follows: