简体   繁体   中英

Beginner java for-loop

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.

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 .

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM