+ 1

Can someone pls explain the output of this snippet

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

9th Jul 2018, 6:23 PM
Ashay Singh
Ashay Singh - avatar
4 Respostas
+ 1
its printing out x the loop runs 5 times, so 5 times those things happen 1. z > 3? 2. x =x+1 3. x>2? 4. if 1. and 3. are true x is made 7 bigger. if you want to know the output, just use it in the playground.
9th Jul 2018, 6:30 PM
Yannick Reiß
Yannick Reiß - avatar
+ 1
bro I know the output it's 2....that's where I'm stuck.. nd not getting how 2 could be the output
9th Jul 2018, 6:34 PM
Ashay Singh
Ashay Singh - avatar
+ 1
I considered the loop and also can't see how the result could be 2. It starts by saying... x = 0 And the loop says... z = 0 Since z < 5, the loop runs, but inside the loop it asks if z > 3, which is false so the 7 is NOT added. But, by also saying ++x>2, it incremented x by one. So now... x = 1 Now, the next stage of the loops occurs. z is incremented by z++ in the loop paratheses. z = 1 Then same thing happens this time. The 7 isn't added, but x is increment by 1. x = 2 The next loop runs and z is incremented. z = 3 The if statement still isn't satisfied since z>3 is false (it is equal). x is incremented on the if statement to 3 again. x = 3 Now when the loop runs, z is incremented. z = 4 The if statement increments x. x = 4 Both conditions are true so the 7 is added. x = 11 The loop tries to run again but now, z is incremented... z = 5 And the loop stops since z<5 is false. I think the output should be 11. I just ran it and the output was 1. Now I am very confused.
10th Jul 2018, 1:16 AM
James
James - avatar
+ 1
exactly bro I too approached in the same way and got the output as 11...but the compiler shows 2!!
10th Jul 2018, 2:36 AM
Ashay Singh
Ashay Singh - avatar