Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this Java for loop termination condition mean?

I am wondering if anyone here knows what the termination condition in the following for loop is supposed to mean.

for (int i = 0; i < 1 << Level; i++) {
...
}
like image 357
Fisher Man Avatar asked Nov 08 '15 06:11

Fisher Man


2 Answers

<< shifts the bits of the first operand n times to the left, where n is the second operand.

Therefore 1 << Level shifts the single 1 bit of the number 1 Level times to the left, which is equivalent to calculating 2 ^ Level.

So i < 1 << Level is equivalent to i < Math.pow(2,Level).

like image 134
Eran Avatar answered Nov 01 '22 11:11

Eran


Simply stated

for (int i = 0; i < 1 << Level; i++) {
...
}

is equal to

for (int i = 0; i < Math.pow(2,Level); i++) {
...
}

So the for loop will run for "Math.pow(2,Level)" times since you are counting from 0 to Math.pow(2,Level)-1.

if Level = 2 then the loop is

for(int i =0;i<4;i++){}

if Level = 3 then the loop is

for(int i =0;i<8;i++){}

if Level = 5 then the loop is

for(int i =0;i<32;i++){}
like image 29
Doc Avatar answered Nov 01 '22 10:11

Doc