Reputation: 17
my program and question are below
public class test {
public static void main(String[] args) {
int x = 0;
int y = 0;
while ( x < 5 ) {
y = x - y;
System.out.println(x + "" + y);
x = x+1;
}
}
}
So output for this is 00 11 21 32 42. I understand what happens when x is even but what when x is odd? Let's move to step 2 and make x=1, then we get
y=1-y
2y=1
y=1/2
For me output should be like 11/2 or sth like that So how the hell output for this is 11? Do we use approximation? Thanks for answer.
Upvotes: 0
Views: 189
Reputation: 1754
Isn't it obvious? By "=" you assigning new value into variable.
x = 0, y = 0
y = 0 - 0 = 0
print x y -> 0 0
x = 1, y = 0
y = 1 - 0 = 1
print x y -> 1 1
x = 2, y = 1
y = 2 - 1 = 1
print x y -> 2 1
etc...
Upvotes: 1
Reputation: 122006
No. You understand it wrong. You are doing math keeping the fact aside that evaluation of Java expression.
y = x - y;
means
y= 1-0;
Which is
y = 1
Upvotes: 5
Reputation: 9806
There's nothing off with your code, the result is correct. When x
is 1, we set y
to be equal to x
- y
. That means x
and y
are both 1, as 1 - 0 is 1. Remember that a = b
in programming is an assignment and does not imply equality.
Upvotes: 2