12,247 views
32 votes
32 votes

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

Let $n = 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 $i^{th}$ iteration is:

  1. $n=d_1\, d_2 \,\ldots\, d_{m-i} \qquad \mathbf{and} \qquad \text{rev} = d_m\,d_{m-1} \,\ldots\, d_{m-i+1}$

  2. $n= d_{m-i+1} \,\ldots\, d_{m-1}\, d_m \qquad \mathbf{or} \qquad \text{rev} = d_{m-i} \,\ldots\, d_2\,d_1$

  3. $n \neq \text{rev}$

  4. $n=d_1\, d_2 \,\ldots\, d_m \qquad \mathbf{or} \qquad \text{rev} =d_m \,\ldots\, d_2\, d_1$

5 Answers

1 votes
1 votes
Hello sir,

I have taken n=128,  after running code I got below output at each iteration:

Iteration 1(n=12, rev=8)

Iteration 2(n=1, rev=82)

Iteration 3(n=0, rev=821)

Now, as above output I can conclude that option c(n!=rev) should be right answer.

Please clarify if observed something wrong, thanks!
Answer:

Related questions

26 votes
26 votes
5 answers
1
Kathleen asked Sep 18, 2014
7,021 views
Choose the best matching between the programming styles in Group 1 and their characteristics in Group 2.$$\begin{array}{|ll|ll|}\hline \rlap{\textbf{Group 1}} & & \rlap{...
24 votes
24 votes
3 answers
4
Kathleen asked Sep 12, 2014
4,535 views
Consider the following PASCAL program segment:if i mod 2 = 0 then while i >= 0 do begin i := i div 2; if i mod 2 < 0 then i := i - 1; else i := i – 2; end;An appropria...