Reputation:
this code:
for(int i=5; i<50; i=i*2){
}
Why does it loop 4 times instead of 3? I thought it did 5x2 which = 10, then 10 x 2 which = 20, then 20 x 2 which = 40, and stops there since 40 x 2 is greater than 50.
Upvotes: 2
Views: 107
Reputation: 1079
Well, the start:
if i < 50 --> do a iteration
i=5
--> less than 50 --> first loop;
Now the increment of i
--> i = i*2
--> i = 5*2 = 10
i=10
--> less than 50 --> second loop;
Now the increment of i
--> i = i*2
--> i = 10*2 = 20
i=20
--> less than 50 --> third loop;
Now the increment of i
--> i = i*2
--> i = 20*2 = 40
i=40
--> less than 50 --> fourth loop;
Now the increment of i
--> i = i*2
--> i = 40*2 = 80
i=80
--> bigger than 50 --> stop
Upvotes: 1
Reputation: 61198
Print the numbers:
for (int i = 5; i < 50; i = i * 2) {
System.out.println(i);
}
Output:
5
10
20
40
So you are missing the first iteration when i == 5
.
Incidentally, i = i * 2
can be written as i *= 2
.
Upvotes: 4
Reputation: 301
The first execution uses the assigned value of i
. It only iterates after executing. So it will run once before the three times that you have listed.
Upvotes: 2
Reputation: 880
On the first iteration i
is 5.
The second time it loops, i
is 10.
The third time i
is 20.
After the third iteration i
is 40. Has i
passed 50 yet? No.
After the fourth iteration i
is 80, and we exit the loop.
That makes 4 iterations.
Upvotes: 1