Skip to content
Official PYQ · 2004

GATE CS 2004 Q32 — Programming in C

Explain with AI

Consider the following program fragment for reversing the digits in a given integer to obtain a new integer.

Let n=d1 d2 … dmn = d_1\, d_2\, \ldots\, d_m.

int n, rev;
rev = 0;
while(n > 0) {
    rev = rev * 10 + n%10;
    n = n/10;
}

The loop invariant condition at the end of the ithi^{th} iteration is:

Choose one option
View worked solution

Answer: A

A loop invariant is a condition that holds true before and after each iteration of a loop.

Let the initial value of nn be represented as a sequence of mm digits: n=d1d2…dmn = d_1 d_2 \ldots d_m.

Let us trace the values of nn and rev\text{rev} at the end of the first few iterations:

  • Before the loop starts (i=0i = 0):
    • n=d1d2…dmn = d_1 d_2 \ldots d_m
    • rev=0\text{rev} = 0
  • At the end of the 1st1^{\text{st}} iteration (i=1i = 1):
    • rev=0×10+(n%10)=dm\text{rev} = 0 \times 10 + (n \% 10) = d_m
    • n=n/10=d1d2…dm−1n = n / 10 = d_1 d_2 \ldots d_{m-1}
  • At the end of the 2nd2^{\text{nd}} iteration (i=2i = 2):
    • rev=dm×10+dm−1=dmdm−1\text{rev} = d_m \times 10 + d_{m-1} = d_m d_{m-1}
    • n=d1d2…dm−2n = d_1 d_2 \ldots d_{m-2}

By induction, at the end of the ithi^{\text{th}} iteration:

  • The remaining number nn has its last ii digits removed: n=d1d2…dm−in = d_1 d_2 \ldots d_{m-i}
  • The variable rev\text{rev} contains the last ii digits of the original number in reverse order: rev=dmdm−1…dm−i+1\text{rev} = d_m d_{m-1} \ldots d_{m-i+1}

Both of these conditions must hold simultaneously (connected by an and operator).

Thus, the loop invariant at the end of the ithi^{\text{th}} iteration is:

n=d1d2…dm−iandrev=dmdm−1…dm−i+1n = d_1 d_2 \ldots d_{m-i} \qquad \mathbf{and} \qquad \text{rev} = d_m d_{m-1} \ldots d_{m-i+1}

This matches Option A.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions