Skip to content
Advertisement

Why is while loop treated true if condition is false?

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,

  1. Now value of i=5(in memory), inside while(5>0), it prints 4.

  2. Now value of i=4(in memory), inside while(4>0), it prints 3.

  3. Now value of i=3(in memory), inside while(3>0), it prints 2.

  4. Now value of i=2(in memory), inside while(2>0), it prints 1.

  5. Now value of i=1(in memory), inside while(1>0), it prints 0.

Hope now you are clear to go ahead. Gud Luck.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement