user4724687
user4724687

Reputation:

Java while loop nested in a for loop.

I have this simple code sample that I don't understand.

// Compute integer powers of 2.

class Power {
    public static void main (String args[]) {
        int e, result;

        for (int i = 0; i < 10; i++) {
            result = 1;
            e = i;
            while (e > 0) {
                result *= 2;
                e--;
            }
            System.out.println("2 to the " + i + " power is " + result);
        }
    }
}

Producing this output.

2 to the 0 power is 1
2 to the 1 power is 2
2 to the 2 power is 4
2 to the 3 power is 8
2 to the 4 power is 16
2 to the 5 power is 32
2 to the 6 power is 64
2 to the 7 power is 128
2 to the 8 power is 256
2 to the 9 power is 512

Questions:

  1. How come result is not always 2, since it's being re-initialized every time the for loop is entered?

  2. The e-- decrement doesn't do a thing either, does it? Since, again, e is being set equal to i afresh on every iteration.

Thanks.

Upvotes: 0

Views: 94

Answers (3)

Jean-Fran&#231;ois Savard
Jean-Fran&#231;ois Savard

Reputation: 21004

How come result is not always 2, since it's being re-initialized every time the for loop is entered?

Yes, it is being re-initialized but only in the first loop. Your inner loop is looping while(e > 0) and double result at each iteration. Then once you are done looping, you pring the result and restart. The value of result will depend on e which define the number of times result is doubled.

The e-- decrement doesn't do a thing either, does it? Since, again, e is being set equal to i afresh on every iteration.

Again, yes it is being set back to i at each iteration but that doesn't mean it is useless. At each iteration, e is set back to the new value of i, and then you use it to create an inner loop while e > 0 where at each iteration you decrement e of 1 and double the result.

Upvotes: 1

Mark
Mark

Reputation: 1498

The two questions kind of go together.

You see, e is set to i which is actually INCREASED each iteration. And the higher e is, the more often the inner while will be worked through.

So for example in your 3rd for iteration

i = 2
e = 2
result = 1

So first while:

result = result*2 = 1*2 = 2
e = 1

e is still > 0 so after the second while:

result = result*2 = 2*2 = 4
e = 0

And there we go.

e-- did something twice and result is NOT 2.

Upvotes: 1

chepner
chepner

Reputation: 531135

result and e are re-initialized at the top of the for loop, but are modified within the while loop before result is displayed at the bottom of the for loop.

Upvotes: 0

Related Questions