+ 2
The output of this code is 9. But I don't know how.. plzz explain.
int x=0 ; int y=0; for (int z=0; z <5;z++;) { if ((++x > 2> && (++y > 2)) { x++; } } System.out.print(x + y) ;
2 Antworten
+ 5
First of all, there are two errors. The 3rd for statement should not have a ";" and in "++x>2" after the 2 is a > when there should be a parenthesis. However the result is 9.
The reason is the && operator. && skips the second condition if the first one is false, because it will result in false regardless of the result of the second condition. In the first 2 rounds of the loop "++x>2", the result is "false", therefore ++y is never executed. On the third round and onward, "++x>2" is "true" so the program starts executing ++y.
The program ends with x=6 and y=3. Hope it helps.
+ 1
Nice. Is it a question from quizz (from challenges)? How many seconds given to find out that answer? I was once asked for an example of question that have to short timer to solve it, I couldn't answer 'cause I haven't been writing them down (I was busy trying to solve them☺). Somewhy I'm sure that for this one question it's no more than 15 seconds or so, and then 99.9% of sololearners are not able to solve this question when they get it for the first time (while it's easy enough question but only if you have enough time for the first time to recognize what's happening and to make those iterations in mind not to lose a condition when another one "x-incremention" starts to add), then it's another one question that strongly benefits those who plays often and already memorized such questions (even if they don't undertand why it's 9)... P.S. But overall the question is nice. :-)