Questions: Loop Design and Invariants

5 questions to test your understanding

Score: 0 / 5
Question 1 Multiple Choice

A loop maintains the invariant: 'At the top of each iteration, max_so_far holds the maximum of arr[0..i-1].' The loop runs from i=0 to i=n. What does the invariant tell us after the loop completes?

ANothing — invariants are internal reasoning tools and make no guarantees about the final state
BThat max_so_far equals the maximum of the entire array arr[0..n-1]
CThat max_so_far equals arr[n-1], the last element examined
DThat the loop ran without errors, but the correctness of max_so_far depends on the loop body
Question 2 Multiple Choice

A developer has a loop that passes most test cases but fails intermittently. What should they do first, according to loop invariant methodology?

AAdd more print statements to trace variable values during execution
BGenerate a larger random test suite to identify the failing input pattern
CExplicitly state the intended loop invariant and verify it holds at initialization, is maintained by each iteration, and implies the correct result at termination
DRewrite the loop using a different algorithmic approach
Question 3 True / False

A loop invariant must hold true before the very first iteration of the loop executes.

TTrue
FFalse
Question 4 True / False

A loop invariant is a condition whose variable values remain constant (unchanged) throughout nearly every iteration.

TTrue
FFalse
Question 5 Short Answer

Explain how thinking about loop invariants can help you design a loop correctly in the first place, rather than just verifying a loop after writing it.

Think about your answer, then reveal below.