Why is 150? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

Why is 150?

int x = 100; int y = 200; while(++x < --y){} system.out.print(x);

30th Jan 2018, 2:11 AM
KRod17
KRod17 - avatar
7 Answers
+ 21
loop will run 49 times ... ie 149 <151 [true] //after 49th time ... when it goes to check condition for running it for 50th time ...ie ++149 <--151 or 150 <150 [false] //so x & y will both become 150
30th Jan 2018, 3:29 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 7
while loop continues to iterate until the condition becomes false.Here the x and y are pre-incremented and pre-decremented respectively.So 1st iteration: 101<199 (true) 102<198 (true) ................ 149<151(true) 150<150(false) So when condition becomes false, the while loop will stop iterating printing the current value of x which is 150. you can also try: System.out.println(y); //outputs 150
30th Jan 2018, 2:50 AM
Sunil Thakali
Sunil Thakali - avatar
+ 7
Note that post increment and post decrement will produce different result. while(x++ < y--) System.out.println(x) //outputs 151 System.out.println(y) //outputs 149 Why? post increment first use the value then updates after. 1st Iteration :100<200 (true) 101<199 (true) ......... 150<150(false) now when printing it updates value as x=151 and y=149 Try with different combination in playground and analyze it will help you understand.
30th Jan 2018, 3:02 AM
Sunil Thakali
Sunil Thakali - avatar
+ 5
understood. with sololearn playground the ouputs is 150... thanks so much.
30th Jan 2018, 3:21 AM
KRod17
KRod17 - avatar
+ 4
thanks everyone. but when i run the program in ms-dos the ouputs in X is 149 :s
30th Jan 2018, 3:08 AM
KRod17
KRod17 - avatar
+ 3
What you have done is set a while loop that doesn't stop until the value of x is greater than or equal to that of y. What is does is increment x while simultaneously decrementing y, which therefore results in x being equal to 150 (as with y). Hope this cleared that up! d:
30th Jan 2018, 2:31 AM
Faisal
Faisal - avatar
+ 3
pre increment and post increment result discrepancy in ms-dos ...try with online compilers if you do not have IDE..Can't you try solo learn playground?
30th Jan 2018, 3:14 AM
Sunil Thakali
Sunil Thakali - avatar