Reputation: 19
In this example:
int i = 1;
while(i < 10)
if(i++%2 == 0)
System.out.println(i);
Why is the output 3,5,7,9
and not 2,4,6,8
?
Upvotes: 0
Views: 135
Reputation: 2039
The ++ operator applied after a variable returns the value of the variable and increments the variable after the expression is evaluated. The semantic is the same than this:
int i = 1;
while(i < 10) {
boolean cond = i % 2 == 0;
i = i + 1;
if(cond) {
System.out.println(i);
}
}
Upvotes: 2
Reputation: 119
The post-increment operator, uses the current value of its operand in the expression and then increments it.
We can break this down using a literal value of '2' for example. Basically this is what your present code is doing:
int i = 2;
if (i % 2 == 0) //true, 2 % 2 = 0
i = i + 1; //i now becomes 3
System.out.println (i);
OR to make it simpler, if we remove the loop and put back your code
int i = 1;
if (i++ % 2 == 0) //1 % 2 != 0
System.out.println (i); //Nothing will print for the if statement
System.out.print i; //Will print 2, because this print statement is outside
//the body of the if-statement
to get the output that you are looking for, you will have to use the prefix-increment operator (++i)
int i = 1;
if ( ++i % 2 == 0)
System.out.println (i);
this is equivalent to
int i = 1
if ( (i + i) % 2 == 0) //++i increments i and then uses it in the expression
System.out.println (i);
Upvotes: 0
Reputation: 393811
The condition is performed on the previous value of i
, before it is incremented (which is even), but the output is done on the incremented value of i
(which is odd).
Upvotes: 4