You now know how to implement your logic using a while loop. Just like the while loop, there is another loop called the do-while loop. The loop logic, a starting point, a continuation condition, and a stopping point are similar to what you learnt in the previous lectures.
So you now know how to use while and do-while loops. The basic logic for these loops remains the same, the only difference being that the loop continuation condition is evaluated before the first iteration in case of “while” loop and after the first iteration in case of “do while”.
Let us now take a look at Java code to implement do-while loops.
Please download the file below used in the following video.
One last kind of loop which we'll be talking about is known as the do while loop. So basically the do while loop is much similar to the while loop and the only difference is that the do while loop executes at least once irrespective of whether the condition is true or no. So while the general template of the while loop used to be something like this, that while condition holds true, then do some action, there is some statement which needs to be executed. So this was the general rule for the while loop. In case of the do while loop, we can write that do statement that is take some action while some condition holds true. So basically, if you observe carefully, the only essential difference between a while loop and a do while loop is that irrespective of the while condition which is written here, this statement gets executed once and then we check the while condition. So basically here in the while loop we had that we first check the condition and then execute the statement. Whereas in case of the do while loop, it is equivalent to this at first the statement is executed, then the while loop comes here.
So this is the equivalent of the do while loop here do statement that is take some action and after that keep on checking whether the condition holds true or no. So what can be an example for this? A simple example would be that you take out your car from your garage and you say that keep on driving the car till the destination is reached. So basically you say that do keep driving while destination is not reached. So this basically means that you start the car when you take out the car from your garage and you keep on driving. And after that you keep on checking whether destination is arrived or no. As soon as the destination is arrived, you can stop driving because then this condition would be false. So this is an example of where you can use the do while loop.
Do-while loop is similar to while loop but executes at least once regardless of the condition being true or false.
In a while loop, the statement is executed only if the condition holds true.
In a do-while loop, the statement is executed first and then the condition is checked.
A simple example of a do-while loop is driving a car to a destination until it is reached.
The loop continues until the condition is false.