ProgrammingVery hardProduct company OA

Assume IEEE-754 single-precision float with float arithmetic done in float. Which loops terminate?

Assume IEEE-754 single-precision float with float arithmetic done in float. Which loops terminate?
int c1 = 0, c2 = 0;
for (float f = 0; f != 1.0f; f += 0.25f) c1++;   /* (i)  */
for (float f = 0; f != 1.0f; f += 0.1f)  c2++;   /* (ii) */
  1. A. Neither
  2. B. Only (i), after 4 passes
  3. C. Only (i), after 5 passes
  4. D. Both: (i) after 4 passes and (ii) after 10

Correct answer: B. Only (i), after 4 passes

0.25 is a power of two, exactly representable, so f hits 1.0 exactly after 4 additions. 0.1 has no exact binary form; ten rounded additions give 1.0000001, not 1.0, and the != test never becomes false. Use < or an integer counter for such loops.

More C Programming questions

Exams that ask this topic