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 and 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 .
Let us trace each iteration of the loop:
- Before loop: .
- Iteration 1: Check (True). Inside loop: ; . Print 1.
- Iteration 2: Check (True). Inside loop: ; . Print 2.
- Iteration 3: Check (True). Inside loop: ; . Print 3.
- Iteration 4: Check (True). Inside loop: ; . Print 4.
- Iteration 5: Check (True). Inside loop: ; . Print 5.
- Iteration 6: Check (False, because the inequality is strict: is false). The loop terminates.
Therefore, the printf statement is executed and sum is printed exactly 5 times.
5
Treating the loop condition as 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.