In the previous lesson, we learned about the while loop and how it is implemented. However, one of the restraints when using a while loop is that if the condition does not evaluate to true, that the code within the brackets of the while statement will not execute at all.
However, what if we wanted a while statement that would at least always execute its code once? In this lesson we will learn about the do while loop which allows us to do just that.
In a do while loop, we put the code that we want executed within the do brackets, and then the while condition at the end, but without brackets. Look at the pseudocode for a better understanding.
Code that executes for every loop until the condition evaluates to false and typically has a increment operator involved. (Always executes at least once.) }
while(condition evaluates to true, and then exits the loop once it does not)
Having a basic idea of the syntax now, let’s look at an example.
See how unlike the standalone while loop, there are no brackets associated with the
while. Instead, they are used with the
do statement. Let’s look at what we get back from Java after running this code.
Just like we saw in the normal while loop in the last lesson, it starts at one and then stops once one variable is no longer larger than the other variable. However, there is one key difference to do while loops that we have yet to see. So I am going to change
int numOfChairs = 6 and keep the
numOfGuests = 6. Look at the code below:
Even though the condition is no longer true in our
while loop, the
do block is still going to execute once. So it is no surprise when we get the following output from Java.
Be sure to know that the major difference between the
do while loop is that the do
while loop will always execute the code within the
do statement at least once, whereas the code within a
while statement only will execute if the condition evaluates to true.