GATE / CS ARCHIVE

GATE CSE 2019 / QUESTION 52

Tracing a strict floating-point loop test

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2019 paper

GATE 2019, Q52 2 marks · NAT
Report issue

Control Flow & Loop Tracing

Question 52, GATE 2019: The C program initializes float sum=0.0,j=1.0,i=2.0 and repeats while(i/j>0.0625) { j=j+j; sum=sum+i/j; printf("%f\n",sum); }. How many times is sum printed?
Tap to enlarge
Answer & solution

Official answer: 5

Step through it (26 steps)

1. The loop test is evaluated before doubling j. Variable i remains 2 throughout, while j doubles once per successful iteration. The threshold is 0.0625=1/16.
2. At successive tests, j is 1,2,4,8,16,32, giving i/j equal to 2,1,1/2,1/4,1/8,1/16. The first five values are strictly larger than 1/16; the sixth is equal and fails the > comparison.
3. Each of those five successful tests enters the body exactly once, executes one printf, and changes j to the next power of two. Therefore there are 5 prints.
4. As a check on operation order, the terms added inside the body use the already doubled j: 1,1/2,1/4,1/8,1/16. The printed sums are 1,1.5,1.75,1.875,1.9375, normally shown with six digits after the decimal by %f.
5. The test that stops execution produces no print. These powers of two and binary fractions are exactly representable in ordinary binary floating point, so rounding does not alter this stopping point.

Original paper, page 15 · Answer key