+ 4

Confirmation on challenge question

I came across this question in a challenge, and I have doubt on what the correct answer was, the language is c# and the code goes as follow int x = 2; int y = 5; if (x < y || ++y == 6){ y -= x; } console.write(y); I think the answer is 4 but it was instead 3 both i and my challenger got it wrong. can someone explain why it is 3 to me

11th Dec 2017, 5:38 PM
olufemi jolugbo
olufemi jolugbo - avatar
2 odpowiedzi
+ 10
Good question! This is a little logical, did you notice the if statement in the code? It uses the || operator in between the two conditions and thus, what the compiler does is checks for the first condition (i.e. x < y) and if it is true, moves on executing the compound block of code without letting it check if (++y == 6) as well. Hence, y doesn't gets incremented! P.S. "y" remains 5 and is subtracted from 2 to get the output as 3. If it would have used the && operator instead, the output would've been 4 as it then should check both the conditions to be true. That is, if (x < y && ++y == 6){ y -= x; // now y becomes 4 }
11th Dec 2017, 5:46 PM
Dev
Dev - avatar
+ 2
brilliant Dev, that explains it thanks a lot
11th Dec 2017, 11:24 PM
olufemi jolugbo
olufemi jolugbo - avatar