Question

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 ________.

Official answer and solution
Official answer
5
From
Official GATE 2019 answer key

Solution

Trace the values of variables ii and jj across iterations of the while loop to determine the exact number of iterations before termination.

We are given the code:

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);
}

Note that 0.0625=116=2−40.0625 = \frac{1}{16} = 2^{-4}.

Let us trace each iteration of the loop:

  • Before loop: i=2.0,j=1.0i = 2.0, j = 1.0.
  • Iteration 1: Check i/j=2.0/1.0=2.0>0.0625i/j = 2.0 / 1.0 = 2.0 > 0.0625 (True). Inside loop: j=1.0+1.0=2.0j = 1.0 + 1.0 = 2.0; sum=0.0+2.0/2.0=1.0sum = 0.0 + 2.0/2.0 = 1.0. Print 1.
  • Iteration 2: Check i/j=2.0/2.0=1.0>0.0625i/j = 2.0 / 2.0 = 1.0 > 0.0625 (True). Inside loop: j=2.0+2.0=4.0j = 2.0 + 2.0 = 4.0; sum=1.0+2.0/4.0=1.5sum = 1.0 + 2.0/4.0 = 1.5. Print 2.
  • Iteration 3: Check i/j=2.0/4.0=0.5>0.0625i/j = 2.0 / 4.0 = 0.5 > 0.0625 (True). Inside loop: j=4.0+4.0=8.0j = 4.0 + 4.0 = 8.0; sum=1.5+2.0/8.0=1.75sum = 1.5 + 2.0/8.0 = 1.75. Print 3.
  • Iteration 4: Check i/j=2.0/8.0=0.25>0.0625i/j = 2.0 / 8.0 = 0.25 > 0.0625 (True). Inside loop: j=8.0+8.0=16.0j = 8.0 + 8.0 = 16.0; sum=1.75+2.0/16.0=1.875sum = 1.75 + 2.0/16.0 = 1.875. Print 4.
  • Iteration 5: Check i/j=2.0/16.0=0.125>0.0625i/j = 2.0 / 16.0 = 0.125 > 0.0625 (True). Inside loop: j=16.0+16.0=32.0j = 16.0 + 16.0 = 32.0; sum=1.875+2.0/32.0=1.9375sum = 1.875 + 2.0/32.0 = 1.9375. Print 5.
  • Iteration 6: Check i/j=2.0/32.0=0.0625>0.0625i/j = 2.0 / 32.0 = 0.0625 > 0.0625 (False, because the inequality is strict: 0.0625>0.06250.0625 > 0.0625 is false). The loop terminates.

Therefore, the printf statement is executed and sum is printed exactly 5 times.

Final answer

5

Common trap

Treating the loop condition as ≥0.0625\ge 0.0625 instead of strict inequality >>, which would allow a 6th iteration.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2019 Computer Science and Information Technology (CS)
Question
62 of 65, printed as CS Q.52
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.