I am working my way through "Java - A beginners guide by Herbert Schildt". I hope this question is not way too ridiculous. It is about a while loop condition, where the while loop is located inside a for loop. The code example is this one:
public static void main(String[] args) {
int e;
int 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);
}
}
I don't understand the decrementing of e, within the scope that is written after while (e > 0). Since e = i, and i is incremented, i believe e should be larger than 0 after the for loop has been performed the first time. If e is not decremented, the program will not run properly. Why is decrementing e necessary in this example?
while (e > 0)will always evaluate to true, so you will have an endless loop.If e is not decremented, the program will not run properly. Why is decrementing e necessary in this example?... because the program will not run properly if it isn't decremented. You answered the question yourself.System.out.println(e)after e is decrements and run the code, it should become clear.