+ 2
How y has the value 2 instead of 4?
Java looping https://code.sololearn.com/c1P2W3SbRv7q/?ref=app
4 Réponses
+ 3
&& check second condition only when first condition become true.
In this case x=0,y=0
z=1=> x=1,y=0(first condition false, so don't go to check second condition)
z=2=>x=2,y=0
z=3=>x=3,y=1(from here first condition true, so it start check second condition)
z=4=>x=4,y=2
+ 2
if((++x>2)&&(++y>1))
In the statement above, ++x and ++y would only get incremented when it's satisfies the condition ((++x>2) && (++y>1)).
iteration: if((++x>2)&&(++y>1))
1st :
(++x>2) gets executed giving us x=1 but since we have && in our if condition - this (++y>1) gets skipped because for &&(AND) both condition must be true, so in our case its useless to even execute and check for this (++y>1) when (++x>2) is false
x=1, y=0
2nd :
similarly, (x++>2) gets executed making x=2 but (++x>2) 2>2 is false and (++y>1) is skipped
x=2, y=0
3rd :
(++x>2) makes x=3 and also (++x>2) is true and hence now (++y>1) will gets it chance to get executed making y=1
x=3, y=1
4th :
again (++x>2) gets executed making x=4 and is true so even (++y>1) will be executed making (y=2)
Note: here both conditions in the if condition is true, therefore if blocks get executed making (x=5)
Hence, leaving us with x=5, y=2
+ 2
For z = 1, true:
++x > 2 == 1 > 2 == false
++y is not excuted bcoz of &&, z++;
For z = 2, true:
++x > 2 == 2 > 2 == false
++y is not excuted bcoz of &&, z++;
For z = 3, true:
++x > 2 == 3 > 2 == true
++y > 1 == 1 > 1 == false
whole condition is false, z++;
For z = 4, true:
++x > 2 == 4 > 2 == true
++y > 1 == 2 > 1 == true
whole condition is true, x++, z++;
For z = 5, false:
break;
Output: x = 5, y = 2, z = 5
+ 1