+ 1

Explain this code?

int x = 0; int y = 0; for(int z =1; z<5;z++){ if((++x>2) && (++y>1)){ x++; } } System.out.println(x+ "" +y); I don't understand this code.

23rd Nov 2018, 2:39 PM
Nitin Gutte
Nitin Gutte - avatar
2 Answers
+ 9
way 1) ● Outer for loop will run 4 times [ie for z = 1,2,3,4] ● NOTE : a && b , where a & b are condition ... in that case if 1st condition a is false , then no need to check 2nd condition that is b here : as answer will be false only [it is called short-circuiting] ● for z=1 : 1 is NOT > 2 (no need to check ++y>1) // x=1,y=0 for z=2 : 2 is NOT > 2 (no need to check ++y>1) //x=2,y=0 for z=3 : 3 > 2 now checking ++y>1(1 is NOT >1) // x=3,y=1 for z=4 : 4 > 2 && 2>1 so .. x=4 & y=2 , since whole condition becomes true so x++; will also execute ...ie x=5 & y=2 . //prints 52 way 2)[alternatively] ● see that U have number of times loop will run is 4 ● see that number of times increment is needed in x to make 1st condition true is 3 , so check & do increment in y in 3rd time //x=3,y=1 ● 4th time , both condition will satisfy so inner statement will also execute //ie , x=5 & y=2
23rd Nov 2018, 3:55 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 2
In the if the x and y get an augment. The y variabel only get augmented when the x > 2 is true.
23rd Nov 2018, 3:01 PM
David LĂ©vy