When would a do-while loop be the better than a while-loop?

Viewed 11331

This is a highly subjective question, so I'll be more specific. Is there any time that a do-while loop would be a better style of coding than a normal while-loop?

e.g.

int count = 0;
do {
   System.out.println("Welcome to Java");
   count++;
} while (count < 10);`

It doesn't seem to make sense to me to check the while condition after evaluating the do-statement (aka forcing the do statement to run at least once).

For something simple like my above example, I would imagine that:

int count = 0; 
while(count < 10) { 
   System.out.println("Welcome to Java"); count++;
}

would be generally considered to have been written in a better writing style.

Can anyone provide me a working example of when a do-while loop would be considered the only/best option? Do you have a do-while loop in your code? What role does it play and why did you opt for the do-while loop?

(I've got an inkling feeling that the do-while loop may be of use in coding games. Correct me, game developers, if I am wrong!)

12 Answers

It is very simple to distinguish between the two. Let's take While loop first.

The syntax of while loop is as follows:

// expression value is available, and its value "matter".
// if true, while block will never be executed.
while(expression) {
    // When inside while block, statements are executed, and
    // expression is again evaluated to check the condition. 
    // If the condition is true, the while block is again iterated
    // else it exists the while block.
}

Now, let's take the do-while loop. The syntax of do-while is different:

// expression value is available but "doesn't matter" before this loop, & the 
// control starts executing the while block.
do {
   // statements are executed, and the
   // statements is evaluated and to check the condition. If true 
   // the while block is iterated, else it exits. 
} while(expression);

A sample program is given below to make this concept clear:

public class WhileAndDoWhile {

  public static void main(String args[]) {
    int i = 10;
    System.out.println("While");
    while (i >= 1) {
        System.out.println(i);
        i--;
    }
    // Here i is already 0, not >= 1.
    System.out.println("do-while");
    do {
        System.out.println(i);
        i--;
    } while (i >= 1);
  }
}

Compile and run this program, and the difference becomes apparent.

Related