in Programming in C edited by
5,621 views
6 votes
6 votes

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);
    }
}
  1. 8
  2. 9
  3. 10
  4. 11
in Programming in C edited by
5.6k views

3 Answers

13 votes
13 votes
Best answer

Answer is 11

initial condition j = 1 and i =2

i/j>0.001 ..... j should be >2000

now j increases as 2

So 2n > 2000 i.e 2048

therefor n = 11

for n = 12.... i/j<0.001 so condition false and exits loop

selected by

4 Comments

The number of lines of output will be : it will produce output for 

j= 1 2 4 8 16 32 64 128 256 512 1024  i.e 11 times only. 

 

It will not produce output for j=2048 as while loop will fail. Thus total 11 times.

0
0
initial condition j = 1 and i =2

i/j>0.001 ..... j should be >2000

 

how j  should be greater than 2000?Pls explain, i don’t get it.

Thanks!!
0
0
$i=2.0 , j=1.0$

while condition false at $i/j <= 0.001$

$i<= 0.001*j$

$j>=10^3 * 2$

Suppose loop executes for k iterations then value of $j = {2}^{k-1} $

and at ${(k+1)}^{th}$ iteration loop condition false then, $ j = {2}^{k} $

${2}^{k}>=10^3 * 2$

${2}^{k-1}>=10^3$

$k=11$ (which is same as no. of times loop executed or Lines of output printed.)
0
0
1 vote
1 vote
Its very simple maths used here

i/j > 0.001 holds true

As you can see i=2 always and never changes , while the value of j is constantly changing in terms of 2^n.

2/2^n > 0.001

1/2^(n-1) > 0.001

2^(n-1) < 1000 holds true

it will fail when 2^(n-1)=1024 ,

hence n-1=10

n=11
0 votes
0 votes
Answer is D

4 Comments

@shweta1920: did you tried dry running it? only 11 times it is running after that while condition is false,as stated above
0
0
?.. itz .. 0.001
0
0
@shweta  here question is how many times printf statement executed. so if u run the code u felt that all time j are increasing in the power of 2 while i are fixed which means its like i/2^n>0.001  for n=11 they will enter inside while loop but for n=12 it will make condition false so here only upto n=11  sum value will be printed. so answer is 11
0
0
Answer:

Related questions