Consider the following C program: #include <stdio.h> int main(){ float sum =…

2019

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

Attempted by 287 students.

Show answer & explanation

Correct answer: 5

Answer: 5

Key idea: The loop continues while the ratio i/j is strictly greater than 0.0625. Each iteration doubles j before adding i/j to sum, so j follows powers of two.

  • Iteration 1: initial j = 1, check 2/1 = 2.0 > 0.0625, then j becomes 2 and sum adds 2/2 = 1.0 (printed).

  • Iteration 2: j = 2, check 2/2 = 1.0 > 0.0625, then j becomes 4 and sum adds 2/4 = 0.5 (printed).

  • Iteration 3: j = 4, check 2/4 = 0.5 > 0.0625, then j becomes 8 and sum adds 2/8 = 0.25 (printed).

  • Iteration 4: j = 8, check 2/8 = 0.25 > 0.0625, then j becomes 16 and sum adds 2/16 = 0.125 (printed).

  • Iteration 5: j = 16, check 2/16 = 0.125 > 0.0625, then j becomes 32 and sum adds 2/32 = 0.0625 (printed).

After that, with j = 32 the condition 2/32 = 0.0625 is not strictly greater than 0.0625, so the loop stops. Therefore the sum is printed 5 times.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir