Consider the following C program #include <stdio.h> int main() { float sum =…
2018
Consider the following C program
#include <stdio.h>
int main()
{
float sum = 0.0, j =1.0, i = 2.0;
while(i/j > 0.001) {
j = j + 1;
sum = sum + i/j;
printf ( "%f\n", sum );
}
}How many lines of output does this program produce?
- A.
0-9 lines of output
- B.
10-19 lines of output
- C.
20-29 lines of output
- D.
More than 29 lines of output
Attempted by 341 students.
Show answer & explanation
Correct answer: D
Concept
A while loop tests its condition at the TOP of the loop, using the CURRENT value of the variable, BEFORE the loop body runs. The body executes once for every test that is true. So to count iterations you must find the largest values of the loop variable for which the condition still holds, not assume the loop stops early.
Setting up the condition
Here the controlling variable is j, with i fixed at 2.0. The condition is 2.0/j > 0.001. Solving for j: 2.0/j > 0.001 means j < 2.0/0.001 = 2000. So the loop keeps running as long as j is below 2000.
Tracing the loop
Before the first test, j = 1.0. Check 2.0/1.0 = 2.0 > 0.001 -> true, so the body runs: j becomes 2.0, a value is added to sum, and one line is printed.
The condition is re-tested with the new j each pass. As j grows by 1 every time, 2.0/j shrinks slowly, so the test stays true for a very long range of j.
The test only becomes false once j is no longer below 2000. j takes the values 1, 2, 3, ... while the test is checked, giving on the order of two thousand passes through the body.
Because the printf is inside the loop body, exactly one line is printed per pass, so the number of output lines equals the number of iterations -- roughly 1999 to 2000 lines.
Cross-check
Sanity-bound it: the smallest j that fails the test is around 2000, and j increases by 1 from a start of 1, so the count of successful tests is close to 2000. Two thousand lines is in the thousands, far above any two-digit count, so the output falls in the largest bucket. (Note: the slow 1/j decay is what makes the loop long; nothing forces an early stop after a handful of passes.)