do-while Loops

The do-while loop is similar in function to the while loop, but the conditional test goes in a different place. The following is an example of a do-while loop:

do {
 // the statements inside the loop go here
} while ( gameLives > 0 );

Like the previous while loop, this loop will continue looping until the gameLives variable is no longer greater than 0. The do-while loop is different because the conditional test is conducted after the statements inside the loop, instead of before them. When the do loop is reached for the first time as a program runs, the statements between the do and the while are handled automatically. Then the while condition is tested to determine whether the loop should be repeated. If the while condition is TRue, the loop goes around one more time. If the condition is false, the loop ends. Something must happen inside the do and while statements that changes the condition tested with while, or the loop will continue indefinitely. The statements inside a do-while loop will always be handled at least once. The following statements cause a do-while loop to display the same line of text several times:

int limit = 5;
int count = 1;
do {
 System.out.println("The nurse is not dealing");
} while (count < limit);

Like a while loop, a do-while loop uses one or more variables that are set up before the loop statement. The loop displays the text The nurse is not dealing four times. If you gave the count variable an initial value of 6 instead of 1, the text would be displayed once, even though count is never less than limit. If you're still confused about the difference between a while loop and a do-while loop, engage in a little role-playing and pretend you're a teenager who wants to borrow your father's car. If you are a teenager, all the better. There are two strategies that you can take:

  1. Borrow the car first and tell Dad later that you did it.
  2. Ask Dad before you borrow the car.

Strategy 1 has an advantage over Strategy 2: Even if Dad doesn't want to let you use the car, you get to borrow it once. The do-while loop is like Strategy 1 because something happens once even if the loop condition is false the first time while is encountered. The while loop is like Strategy 2 because nothing will happen unless the while condition at the beginning is TRue. It all depends on the situation in your program.

Watch Out!

Sams Publishing makes no warranties express nor implied that your father will be happy if you borrow his car without telling him first.