Programming Fundamentals · Interview question

What's the difference between while and do-while?

A strong answer

while (cond) { body } tests cond before running the body, so if cond starts false, the body never runs, zero is a valid iteration count. do { body } while (cond); runs the body first and then tests, so the body always executes at least once, even if cond is false from the start. The practical distinction is when "always do this once before checking" is the natural flow, input validation prompts ("enter a number until they give a valid one") are the textbook do-while use case, because you must read at least one value before you can validate it.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

while & do-while Loops

Repeating work while a condition holds, and the one case (do-while) where the body has to run at least once before the test.

More while & do-while Loops questions

Browse all 472 interview questions