Consider the following C program: #include <stdio.h> int main() { float sum = 0.0, j = 1.0, i = 2.0; while (i/j > 0.0625) { j = j + j; sum = sum + i/j; printf("%f\n", sum); } return 0; } The number of times the variable sum will be printed, when the above program is executed, is ________ A. 4 B. 5 C. 6 D. 7

GATE 2019 · Programming and Data Structures · Programming In C · medium

Answer: Sum is printed 5 times. Answer: B. 5

  1. Set up the condition: The condition is 2/j > 0.0625. Note the condition is checked BEFORE j is doubled inside the loop body.
  2. Trace iterations: Iteration 1: check 2/1=2 > 0.0625 (T), j becomes 2, sum=0+2/2=1.0, print 1.0. Iteration 2: check 2/2=1 > 0.0625 (T), j becomes 4, sum=1+2/4=1.5, print 1.5. Iteration 3: check 2/4=0.5 > 0.0625 (T), j becomes 8, sum=1.5+2/8=1.75, print 1.75. Iteration 4: check 2/8=0.25 > 0.0625 (T), j becomes 16, sum=1.75+2/16=1.875, print 1.875.
  3. Check termination: Iteration 5: check 2/16=0.125 > 0.0625 (T), j becomes 32, sum=1.875+2/32=1.9375, print 1.9375. Iteration 6: check 2/32=0.0625 > 0.0625 (F) -> loop exits.