Multiple choice

Consider the following program fragment for reversing the digits in a given integer to obtain a new integer. Let n = d1d2... dm. 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 ith iteration is

  1. n = d1d2... dm-i....and rev = dmdm-1..dm-i+1

  2. n = dm-i+1...dm-1dm (or) rev = dm-i...d2d1

  3. n ¹ rev

  4. n = d1d2...dm (or) rev = dm...d2d1

Reveal answer Fill a bubble to check yourself
A Correct answer
Explanation

The loop reverses the integer. After i iterations, the last i digits of n have been moved to the front of rev in reverse order. Thus, n contains the remaining digits and rev contains the reversed prefix.