When reviewing while and for loops, I encountered a couple of loops that would iterate a variable, i, then print it. I am aware of the semicolon giving the while loop an empty body, but does it work the same in for loops?
For example, if I use a semicolon after the for statement in this loop:
int i = 0;
for (i = 0; i < 10; i++);
System.out.println(i + 4);
then the program outputs this:
14
However, when using a semicolon after the while statement in this loop:
int i = 0;
while (i < 10);
i++;
System.out.println(i + 4);
nothing is printed.
Why does this happen? I assume that a semicolon ends the loop, but I could be misunderstanding how these work, and since i was declared and instantiated outside of the loop, there shouldn’t be any issues with scope.
>Solution :
In the code
while (i < 10);
i++;
The i++; statement is not inside the loop, exactly because the semicolon on the previous line ends the loop.
Since there is no code inside the loop, there is nothing that can change the value of i; therefore, i < 10 can’t stop being true; therefore, the loop cannot end; therefore, the code does not reach the i++ line (or the subsequent attempt to display output).
On the other hand, the code
for (i = 0; i < 10; i++);
is roughly equivalent to
i = 0;
while (i < 10) {
i++;
}
The i++ happens after the code inside the for loop body (even if that body uses continue to skip to the next iteration). Here, there is no code inside the for loop body, but the i++ still happens after that "nothing". Thus, i increases each time through the loop; eventually i is no longer < 10 (specifically, it is equal to 10); and the rest of the code proceeds.