+ 7
Why this output come -1????
https://code.sololearn.com/c3n4rxVE1KSn/?ref=app Arun Tomar Fata1 Err0r Sreejith HAWKEYE Helga Hans Larry Gaurav Agrawal
6 odpowiedzi
+ 2
"how its expression come -2"
simple:
https://code.sololearn.com/cdd4Wm4SnsyV/?ref=app
and in details:
https://code.sololearn.com/cO3hwWMnNdr6/?ref=app
+ 21
👉lets go into the concept works here , do simple things to understand ... and then go to good level
//see this to understand the working 👍
public class Program
{
public static void main(String[] args) {
int x=1;
x=x++ + x;
//1++ + 2 = 1+2 = 3
System.out.println(x);
//now x is 3 , we know
x+=x++ + --x + ++x + x;
//3+= (3++ + --4 + ++3 + 4)
//3+= (3+3+4+4) ==> 3+(14) = 17
System.out.print(x);
}
}
+ 6
x-=expresion is equivalent to x = x-expression
expression = -2
x = -3 -(-2) = -3 + 2 = -1
+ 6
Harsh Agrawal ,
In this equation, all the operators have same presendence, so the equation is evaluated from left to right.
x-=(x++)+(--y)+(--x)+(x++)+1+(++x)+(++x)+(x++)+(y++)+(x--);
step 1:
x = -3, y = 4
x-=(x++)
=> x = x (-3) - x++ (-3)
=> x = -3 + 3 = 0
(since x++ is post increment, x remains -3 but changes to -2 in next occurance)
---------------------------------------------------------------------------
step 2:
x= -2 y=4
[x-=(x++)] +(--y)+(--x)+(x++)
=> 0(x) - [--y(3) + --x(-3) + x++(-3)]
=> 0 - (3-3-3)
=> 3
(here 0 represents x from previous calculation)
---------------------------------------------------------------------------
step 3:
x= -2 y= 3
[x-=(x++)+(--y)+(--x)+(x++)] +1+(++x)+(++x)+(x++)+(y++)+(x--)
=> -3(x) - [1 + ++x(-1) + ++x(0) + x++(0) + y++(3) + x--(1)]
=> 3 - [1 - 1 +0 + 0 + 3 + 1]
=> 3 - [3 + 1]
=> 3- 4
=> -1
ref : https://stackoverflow.com/questions/10812779/output-of-expression-in-i-i-in-java
+ 4
or the easier method,
*calculate the RHS part and substract it from initial value of x
eg:
x-=(x++)+(--y)+(--x)+(x++)+1+(++x)+(++x)+(x++)+(y++)+(x--);
=> x-= -3 +3 -3 -3 +1 -1 +0 +0 +3 +1
=> x-= 0 -6 +0 +4
=> x-= -2
=> x= -3- (-2) (since initial value of x was -3)
=> x= -1
EDIT: there were some calculation mistakes in earlier version, now it's cleared
+ 1
how its expression come -2