GATE / CS ARCHIVE

GATE CSE 2004 / QUESTION 32

Invariant for reversing decimal digits

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2004 paper

GATE 2004, Q32 2 marks · MCQ
Report issue

Control Flow & Loop Tracing

Question 32, GATE 2004: An input nonnegative integer has original digits d1 d2 … dm. The fragment is:
int n, rev; /* n contains the input */
rev=0;
while(n>0) {
  rev=rev*10+n%10;
  n=n/10;
}
Which invariant holds after iteration i? Assume integer division and no overflow; digit strings denote numeric values.
Options:
(A) n=d1…d_(m−i) AND rev=d_m d_(m−1)…d_(m−i+1)
(B) n=d_(m−i+1)…d_(m−1)d_m OR rev=d_(m−i)…d2 d1
(C) n≠rev
(D) n=d1 d2…d_m OR rev=d_m…d2 d1
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

1. After i iterations, n is the original prefix d1...dm−i, and rev is the processed suffix in reverse order dm dm−1...dm−i+1, A. Each step removes n’s final digit and appends it to rev.

2. The notation describes numeric digit values, so leading zeros in the reversed suffix do not change the value; assume the input is supplied nonnegative and the reversed value fits int.

3. Teaching check: For input 1234, successive (n,rev) pairs are (123,4),(12,43),(1,432),(0,4321). This verifies both halves of the invariant simultaneously. An OR condition that merely describes the initial or final arrangement does not express the state after every iteration.

Original paper, page 4