In the following code,
int i;
for (i = 0; i < 5 ; i++)
System.out.println("i = " + i);
Why does the for loop skip the first i++ and output
i = 0
i = 1
i = 2
i = 3
i = 4
Instead of
i = 1
i = 2
i = 3
i = 4
Since it is 0 at the beggining and it runs through i++ once before it executes shouldn't i start with 1?
Since it is 0 at the beggining and it runs through i++ once before it executes shouldn't i start with 1?
That is incorrect. The last part of the loop header, i.e. the C
in for (A; B; C)
is executed after the iteration, not before.
So if we unroll the loop, it executes like this:
int i;
i = 0
if (i < 5) {
System.out.println("i = " + i);
i++;
if (i < 5) {
System.out.println("i = " + i);
i++;
... // until the condition is false
}
}
Hence why the first iteration has i = 0
and not i = 1
.
for
to while
An alternative way to express it is by using a while
loop. Basically
A;
for (B; C; D) {
E;
}
F;
is the same as
A;
B;
while (C) {
E;
D;
}
F;
Note how it is first E
and then D
, not the other way around.
So in your case we have
int i;
i = 0;
while (i < 5) {
System.out.println("i = " + i);
i++;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments