GATE / CS ARCHIVE

GATE CSE 1991 / QUESTION 1(vi)

Evenness as a loop invariant

Algorithms · Correctness, Invariants & Design · Full GATE CSE 1991 paper

GATE 1991, Q1(vi) 2 marks · Other
Report issue

Correctness, Invariants & Design

Question 1(vi), GATE 1991: Pascal enters the loop only if i mod 2=0. While i≥0, it replaces i by i div 2, then subtracts 1 if the new i is odd, otherwise subtracts 2. Give an invariant.
Question 1(vi), GATE 1991: Pascal enters the loop only if i mod 2=0. While i≥0, it replaces i by i div 2, then subtracts 1 if the new i is odd, otherwise subtracts 2. Give an invariant.
Tap to enlarge
Answer & solution

Answer: i is even at each loop test (no official key was published)

The outer test establishes evenness before the first loop test. Let j be the quotient after the division in an iteration. If j is odd, j−1 is even; if j is even, j−2 is even. Thus either branch reestablishes the invariant regardless of the parity produced by division. Nonnegativity is the loop guard, not an invariant after the body: for i=0 the body produces −2 and terminates. An even negative initial value skips the loop altogether. The invariant states a preserved property, not a complete description of all reachable values.

Original paper, page 1