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

AlexMTMorgan picture AlexMTMorgan · Dec 9, 2013 · Viewed 8.7k times · Source

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!)

Answer

Enigma picture Enigma · Dec 9, 2013

If you want to read data from a network socket until a character sequence is found, you first need to read the data and then check the data for the escape sequence.

do
{ 
   // read data
} while ( /* data is not escape sequence */ );