Programming Fundamentals · Interview question

What's a loop invariant, and how does it help you reason about a loop?

A strong answer

A loop invariant is a property that's true before the loop starts, remains true after every iteration of the body, and is still true when the loop exits. It's the formal version of "what should always be true at the top of each iteration." For a loop summing an array, the invariant might be "sum equals the total of elements arr[0..i-1]." Identifying the invariant lets you prove the loop is correct without tracing every iteration: if the invariant holds at exit and the exit condition is what you wanted, the result is correct. When you can't state the invariant cleanly, that's a signal you don't fully understand the loop, usually meaning there's a bug.

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
What's a loop invariant, and how does it help you reason about a loop? | EmbeddedPrep.io