Machine-translated by Google. Questions are authored in English.
Top

Discussion

How many lines of output does the following C code produce?

#include <stdio.h>
float i=2.0;
float j=1.0;
float sum = 0.0;
main()
{
    while (i/j > 0.001)
    {
        j+=j;
        sum=sum+(i/j);
        printf("%f\n", sum);
    }
}

 

  • A.8
  • B.9
  • C.10
  • D.11

Answer: D

Correct answer: 11

Each pass doubles j and prints, so the tested quantity \(i/j\) starts at 2 and halves every time: 2, 1, 0.5, 0.25, … The loop continues while it exceeds 0.001. Since \(2/2^{11} = 0.000977\) is the first value at or below the threshold, the test succeeds for \(j = 1, 2, 4, \ldots, 1024\) - eleven passes, and eleven lines.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.