Programming Fundamentals · Interview question

You wrote a while loop and the body never runs. What are the most likely causes?

A strong answer

Three things to check, in order. First, the condition starts false, the variables it tests already have values that make it false before the first iteration; add a printf or step in the debugger to confirm. Second, you put the condition test before initializing the variable, common when you copy/paste loops around. Third, in do-while vs while confusion: a do-while body always runs once, so if "the body never runs" really means "the body runs exactly once when I expected zero," you might be using the wrong form. The systematic fix is to print the values of every variable in the condition right before the loop, so you can see what the condition is actually testing.

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