+ 2

plzzz help!! why the answer is 2 ????

class Demo { public static void main (String[] args) { int x=0; for(int i=10;i>0;i=i-x){ x++; if(i%2==1){ break; } } System.out.print(x); } }

5th Nov 2019, 3:51 PM
Amir allameh
Amir allameh - avatar
5 Réponses
+ 4
Initially, x=0 When loop executes for first time, value of x becomes 1 and i is 10 so the condition i%2==1 becomes false. Now, when loop executes 2nd time, Value of i is i-x = 9 and x gets incremented. Now the condition i%2==1 becomes true and hence, loop breaks. Here, since value of x becomes 2(post increment), 2 is printed. Therefore, output is 2.
5th Nov 2019, 4:06 PM
Chetali Shah
Chetali Shah - avatar
+ 3
Yeah! It was.
5th Nov 2019, 4:10 PM
Chetali Shah
Chetali Shah - avatar
+ 2
Let's start i=10 and i>0 is true so the loop will be executed, now x++ and then the if condition fails because 10%2 is equal to 0 and not to 1, now i=i-x is executed which is i=10-1 since x was incremented before. Now again 9>0 so we go into the loop, again x++ but now the if(i%2==1) is true since 9%2 is 1. So the break statement is executed and it comes out of the loop but remember x was already incremented before coming out of the loop. So it is 2 now. Hence the answer is 2.
5th Nov 2019, 4:04 PM
Avinesh
Avinesh - avatar
+ 2
Chetali Shah that timing was almost perfect.
5th Nov 2019, 4:08 PM
Avinesh
Avinesh - avatar
0
thank u all
5th Nov 2019, 7:51 PM
Amir allameh
Amir allameh - avatar