Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'do...while' vs. 'while'

Possible Duplicates:
While vs. Do While
When should I use do-while instead of while loops?

I've been programming for a while now (2 years work + 4.5 years degree + 1 year pre-college), and I've never used a do-while loop short of being forced to in the Introduction to Programming course. I have a growing feeling that I'm doing programming wrong if I never run into something so fundamental.

Could it be that I just haven't run into the correct circumstances?

What are some examples where it would be necessary to use a do-while instead of a while?

(My schooling was almost all in C/C++ and my work is in C#, so if there is another language where it absolutely makes sense because do-whiles work differently, then these questions don't really apply.)

To clarify...I know the difference between a while and a do-while. While checks the exit condition and then performs tasks. do-while performs tasks and then checks exit condition.

like image 585
mphair Avatar asked Jul 27 '10 19:07

mphair


People also ask

Which is better do while or while?

Do/while should be used when you want to run the code block at least one time. You should use a while loop when you don't know if you even want to run it a single time.

When we use do while?

Using the do-while loop, we can repeat the execution of several parts of the statements. The do-while loop is mainly used in the case where we need to execute the loop at least once. The do-while loop is mostly used in menu-driven programs where the termination condition depends upon the end user.


1 Answers

If you always want the loop to execute at least once. It's not common, but I do use it from time to time. One case where you might want to use it is trying to access a resource that could require a retry, e.g.

do {    try to access resource...    put up message box with retry option  } while (user says retry); 
like image 107
Bob Moore Avatar answered Oct 25 '22 03:10

Bob Moore