views:

172

answers:

1

How many times will the following loop execute?

x=-4
while x <8 
    x=x+3
end

Can anyone explain it to me?

+2  A: 

Code:

x=-4; 
cnt = 0; 
while x <8  
  cnt = cnt+1
  x=x+3;
end

Output:

cnt =

 1

cnt =

 2

cnt =

 3

cnt =

 4

Why?

We know it will run once (since x = -4 when it enters the loop and the condition is x<8).

So, that means, it will quit when

-4+cnt*3 >= 8

And if you simplify that:

cnt >= 4

which means, it will quit when it runs 4 times.

Suppose the condition was while x < 9, then the same equation would solve for

cnt >= 4.333

So you use the integer greater than 4.333, or 5 - so it will run 5 times.

Jacob