I was following an example of how to produce a script in java that computes and prints the powers of 2 (2, 4, 8, 16...) and the script looks like this:
class Power {
public static void main(String args[]) {
int e;
int result;
for(int i = 1; i < 10; i++) {
result = 1; //why doesn't this reset result to 1 for every iteration?
e = i;
while(e > 0) {
result *= 2;
e --;
}
System.out.println("2 to the " + i + " power is " + result);
//I would expect printing "result" here would result in 2 every time...
}
}
}
The output is:
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
My question is that if the result variable is declared as 1 within the initial for loop but outside the inner while loop, how come its value doesn't reset to 1 every time the for loop runs? It's clear to me that the for loop begins running before the while loop takes over, because the System.out.println() command is run every time. What is it about Java's structure that allows this?
You are absolutely right about result
being reset to 1 in each iteration of the for loop. It does get reset.
"But why doesn't printing result
give me 2 every time" you ask.
After result
is being set to 1, and before that iteration of the for loop ends, the while loop runs. How many times does the while loop runs? It depends on i
. In the first iteration of the for loop, the while loop loops once, in the second iteration of the for loop, the while loop loops twice, in the third iteration of the for loop, the while loop loops three times, and so on.
At the end of each iteration of the for loop, result
will contain the value of 2 to the power <however many times the while loop looped for>
. So at the end of the first iteration of the for loop, result
is 2 because the while loop looped only once. At the end of the second iteration, result
is 4 because the while loop ran twice and so result *= 2
is ran twice.
If result
isn't reset, it would have become 8 by the end of the second iteration of the for loop: it got multiplied once in the first iteration, and twice in the second iteration.