Neela Sharuni
Neela Sharuni

Reputation: 77

post increment operation in while loop (java)

Recently i came across this question

int i = 10;
while (i++ <= 10) {
    i++;
}
System.out.print(i);

The answer is 13 , can some please explain how is it 13?

Upvotes: 5

Views: 555

Answers (2)

quirkystack
quirkystack

Reputation: 1407

This is one of the alternative ways I could wrap my head around this. Let f(ref i) be a function which takes in i by reference and increment it it's value by 1. So f(ref i) = i + 1

Now that we have f(ref i), the above code can be written as

int i = 10
while( (f(ref i) -1) <=10 )
{
   f(ref i);
}

I would replace f(ref i) with equivalent i values on its return and get the answer like

while(11 - 1 <= 10) {12}
while (13 -1 <= 10) -> break;

so i = 13.

Upvotes: 1

John3136
John3136

Reputation: 29266

  • i = 10. Look at i, compare to 10
  • i = 10. 10 <= 10, so enter the loop.
  • i = 10. increment i (as per the while expression)
  • i = 11. In the loop, increment i
  • i = 12. Look at i, compare to 10
  • i = 12. 12 is not <= 10, so don't enter the loop.
  • i = 12. Increment i (as per the while expression)
  • i = 13

Upvotes: 9

Related Questions