I am trying to do in Java:
int i=5; while(i-- >0) { System.out.println(i); }
When running this program the output is:
4 3 2 1 0
I am very surprised to see 0
in output. I am new in development. Can anyone justify this?
Advertisement
Answer
Postdecrement/Increment operator works on the principle “Use first and then Change”
Initially value of i=5, when it enters while loop it will compare value of i first and then it prints the decremented value. Here i will show you each iteration along with checks performed in each iteration,
Now value of i=5(in memory), inside while(5>0), it prints 4.
Now value of i=4(in memory), inside while(4>0), it prints 3.
Now value of i=3(in memory), inside while(3>0), it prints 2.
Now value of i=2(in memory), inside while(2>0), it prints 1.
Now value of i=1(in memory), inside while(1>0), it prints 0.
Hope now you are clear to go ahead. Gud Luck.