ProgrammingVery hardProduct company OA

Which of these loops run their body exactly for i = 4, 3, 2, 1, 0 (once each) with an unsigned i?

Which of these loops run their body exactly for i = 4, 3, 2, 1, 0 (once each) with an unsigned i?
for (unsigned i = 5; i-- > 0; )        { /* (i)   */ }
for (unsigned i = 4; i >= 0; i--)      { /* (ii)  */ }
for (unsigned i = 4; i > 0; i--)       { /* (iii) */ }
for (unsigned i = 4; i + 1 > 0; i--)   { /* (iv)  */ }
  1. A. (i) only
  2. B. (i) and (iv) only
  3. C. (ii) and (iv) only
  4. D. (i), (iii) and (iv) only

Correct answer: B. (i) and (iv) only

(i) tests the old value and decrements before the body, so the body sees 4 to 0. (iv) works because after 0, i wraps to UINT_MAX and i + 1 wraps to 0. (ii) never ends, since an unsigned value is always >= 0, and (iii) stops before 0.

More C Programming questions

Exams that ask this topic