in Programming in C retagged by
12,561 views
21 votes
21 votes

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 _________

in Programming in C retagged by
by
12.6k views

4 Comments

5 will be answer
10
10
edited by
Initially

i = 2.0, j = 1.0

J = 1 => i/j = 2/1  > 0.0625 // First print

J = 1+1 => i/j = 2/2 > 0.0625 //second print

J = 2+2 => i/j = 2/4  > 0.0625// Third print

J = 4+4 => i/j = 2/8 > 0.0625 // fourth print

J = 8+8 => i/j = 2/16 > 0.0625 // Fifth print

J = 16+16 => i/j = 2/32 > 0.0625 (False)
8
8
$\mathbf{5}$ times.
1
1
edited by

Use normal calculator and look

2/1 -------------------1

2/(1+1)---------------2

2/(2+2)-------------3

2/(4+4)--------------4

2/(8+8)--------------5

2/(16+16) while condition fails as 0.0625 is not greater than 0.0625

0
0

3 Answers

34 votes
34 votes
Best answer
$i = 2.0, j=1.0$

while $\left( \frac{i}{j} > 0.0625\right)$

$j = 1$
$ \frac{i}{j} = \frac{2}{1}  > 0.0625$
$j=j+j, 1^{\text{st}}$ PRINT

$j=2$
$ \frac{i}{j} = \frac{2}{2}  > 0.0625$
$j=j+j, 2^{\text{nd}}$ PRINT

$j=4$
$ \frac{i}{j} = \frac{2}{4}  > 0.0625$
$j=j+j, 3^{\text{rd}}$ PRINT

$j=8$
$ \frac{i}{j} = \frac{2}{8}  > 0.0625$
$j=j+j, 4^{\text{th}}$ PRINT

$j=16$
$ \frac{i}{j} = \frac{2}{16}  > 0.0625$
$j=j+j, 5^{\text{th}}$ PRINT

$j=32$
$ \frac{i}{j} = \frac{2}{32}  = 0.0625$
$\text{Break}$

Total $5$ times sum will be printed.
edited by

1 comment

Typo  $2/32$
1
1
12 votes
12 votes

5 times while loop will iterate..

7 votes
7 votes

while loop condition is :-

$\frac{2}{2^{k}}> 0.0625$

this condition will be true for k=0,1,2,3,4 but fails for k=5

so it'll print sum 5 times.

 

Answer:

Related questions