Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 745
Neela Sharuni Avatar asked Jul 28 '15 00:07

Neela Sharuni


2 Answers

  • 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
like image 101
John3136 Avatar answered Sep 28 '22 15:09

John3136


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.

like image 45
quirkystack Avatar answered Sep 28 '22 14:09

quirkystack