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 _________
View worked solution
Answer: 5
We can trace the execution of the loop step-by-step. Note that the loop condition is , where . Initially, , , and .
| Iteration | Condition Check () | New () | New () | Printed? |
|---|---|---|---|---|
| 1 | (True) | Yes (1st) | ||
| 2 | (True) | Yes (2nd) | ||
| 3 | (True) | Yes (3rd) | ||
| 4 | (True) | Yes (4th) | ||
| 5 | (True) | Yes (5th) | ||
| 6 | (False) | - | - | No (Loop terminates) |
Thus, the printf statement inside the loop is executed exactly 5 times.
Free practice · Your answers on this page are not saved.
