+ 5

What is the output of this code? Why is the output 2?

int x=0; for(int z=0; z<5; z++){ if((z>2)&&(++x>2)){ x+=7; } } System.out.print(x);

8th Sep 2017, 12:46 PM
Carlos Andres
Carlos Andres - avatar
4 Answers
+ 10
//loop 1 , z=0... 1st condition ie z>2 becomes false ... so not checked for ++x >2 ... bcz for && if one condition goes false then whole will be false // loop2 , z=1,x=0, //loop3 , z=2,x=0, //loop4, z=3 .... 1st condition ie z>2 becomes true ... not it checks 2nd condition .. ie. ++x >2 .. which comes false ... so x+=7 is not executed ... but value of x gets increased by 1 3rd loop , z=3,x=1 //lool5 , z=4 ... x=2 .... again both conditions are checked but since 2nd condition again comed false thats why x+=7; not gets executed hope u like the explanation and got what i want to say â˜ș
8th Sep 2017, 7:05 PM
Changed
Changed - avatar
+ 4
Because z can be greater than 2 just for 2 times in the loop. From when z is greater than 2, it checks next condition and the value of x increases. It's simple.
8th Sep 2017, 4:24 PM
Md. Nafis Ul Haque Shifat
Md. Nafis Ul Haque Shifat - avatar
+ 3
Thanks to all. I was confused because I didn't know to break statement IF in the first condition P.S. I'm sorry with my English. :)
8th Sep 2017, 10:08 PM
Carlos Andres
Carlos Andres - avatar
+ 1
Here is the reason .After 2 loops,z =3,at this time x=1,the next loop,z=4,++x =>x = x+1=2,then next loop;z =5, loop end,x=2;the 2nd case(++x>2)never satisfied.
8th Sep 2017, 5:15 PM
Ran
Ran - avatar