Reputation: 7018
I am not able to figure out how the following code snippet prints 13 as an output. As far as I can see, the while condition should keep looping as i
is always less than 10
in this case. I tried debugging but couldn't it figure out. Can someone please explain?
public class WhileCondition2
{
public static void main(String... args)
{
int i = 10;
while (i++ <= 10)
{
i++;
}
System.out.print(i);
}
}
Upvotes: 2
Views: 4388
Reputation: 7805
You are using post increment
while (i++ <= 10) { // i will be incremented after evaluating i and do comparaison with 10
i++;
}
You can use the pre increment instead of post increment
while (++i <= 10) { // i will be incremented before comparaison
i++;
}
And the value of i
will be 11
.
Upvotes: 8
Reputation: 1207
After i
becomes equal to 10
, it increments once after the checking and i
becomes 11
. Then the increment in the loop body happens making i = 12
. At last the condition is checked where i = 12
and as expected it turns out to be false. But the increment in the condition section will happen never the less. That is why it prints 13
.
Upvotes: 3
Reputation: 2690
i
to 10
would output 10
while i
is less or equals 10
i++
this means the conditions i <= 10
is first inspected and then the increment is done output 11
i
was 10
when starting the loop and is now 11
, and get's then incremented to 12
, would print 12
i = 12
which is more then 10
, loop ends but your i++
is still done after the condition failed, i
is now 13Upvotes: 2
Reputation: 9
Yes the reason the output is 13 is as follows
the stating value of i is 10.
when it enters the while loop i++ <= 10 is true as i == 10 and enters the loop, but before it enters the loop i is incremented to 11 due to the post increment operator.
Once in the loop i is incremented again to 12 again with the post increment operator that is in the loop.
Next the i is tested again in the while(i++ <= 10) and is false as i is 12. but before it exits the loop it is again incremented by the post increment operator that makes it 13.
and this is what is output to the java console window,
The thing to remember with this is even when the while loop condition is false it will still increment the i value.
Hope this helps.
Upvotes: 0
Reputation: 3247
You are incrementing i once in the while statement and once in the loop itself, you should do one or the other.
Upvotes: 1
Reputation: 394146
First iteration :
while (i++ <= 10) { // i++ returns 10, so condition is true, i becomes 11
i++; // i becomes 12
}
Second iteration :
while (i++ <= 10) // i++ returns 12, so condition is false, i becomes 13
Therefore the final value of i
is 13.
Upvotes: 14