0

How While loop in java works even if variable decrement is written inside println method ?

so I came across this code and got confused. int x =5; while(x > 0) { System.out.println(x--); } the output is 5 4 3 2 1 what i couldn't understand in this code is, whatever written inside println get just printed "System.out.println();" but here the value of x is getting assigned repeatedly. how? the final output should have been only 5 4 and then it should have been stopped but it didn't. please explain.

21st Sep 2018, 5:03 PM
Gourav Kundu
1 Réponse
+ 2
Everything looks perfect!! Step 1: the value of x is checked if it is >0 according to while loop then x is 5 when it enters the loop and in println method it prints 5 thn decrease it by 1 Step 2: checks if it is >0 then the same process repeat until the value reaches to 1 Step 3: when the value get decreased from 1 the condn becomes false and it can't enters the while loop and Program terminates
21st Sep 2018, 6:08 PM
Rishabh
Rishabh - avatar