What is a situation when one would use a do...while loop?

I understand the function of a do…while loop. But i was hoping that someone had a concrete situation, real or fake, in which this would function, preferably unrelated to the FCC algorithms. I’m having some trouble wrapping my head around the ‘why’ after I understood the ‘how’.

do { 
  turn off fire alarm
} while (fire not detected)

The difference with this and a normal while loop is that the condition will always run at least once.

1 Like

I kind of feel like this isnt used too toooo often, and was hard pressed to think of specific examples…

Searched around and found this great example…specifically this part:

Let’s consider another scenario where we want to take an integer input from user until user have entered a positive number. In this case we will use a do-while loop like this.

  while(input < 0)

In this case we have to run loop at-least once because we want input from user at-least once. This loop will continue running until user enters a positive number.



Thank you, @JohnnyBizzel!

1 Like

Hey thanks! Didn’t even think of Quora…although tbh, the forum is faster. :sweat_smile:

Just wanted to add, I really do think this is one of those things that isnt so obvious to use…until you need it. Like, even in the example I gave you, while its a perfect case use, my first inclination would have been to first use an if statement to see if user input is not blank, then run a while loop to continue until input > 0.

I posted this funny pic explaining the different between while and do while loops in a community Im in, and lots of people chimed in to say they have never used do…while on the job. The poor do…while is indeed misunderstood :joy: Here’s the pic btw…its cute :smiley:


I wish I could like this more lmao!!! :rofl:

1 Like

A practical example:
Reading records from a database where you don’t know how many records will be returned… or maybe zero records were found.

// do some database query here

// if no database records were returned, 
// or matched the query then skip the whole while...looop

while (NOT mydatabase.EOF)    // if we found some records, do some stuff 
   // do stuff... display record on screen, do calculations on the record, etc.. 
   // do more stuff

  mydatabase.movenext()    // move to the next record, if there is any

wend   // continue doing this until no more records found (i.e. end of file EOF) 
1 Like