why do i get this output ? I expect the output to be 10,9,8…
But it is 11,12,13….
class tester {
static int i = 0;
public static void main(String args[]) {
recursive();
System.out.println("after recursive");
}
public static void recursive() {
while(i++<10) {
recursive();
System.out.println(i);
}
}
}
The simple logic is as follows:
Since your incremental is a posfix increment, the original value is evaluated first, before increment.
Logic:
iis initially0, so,0 < 10(true), increment by 1. Now, callrecursive().This loops (1) until
i = 10. Wheni = 10is evaluated, the while expression isfalse, so it leaves the loop.Remember, we have already called
recursive()10 times already, so it now needs to printi, 10 times, (since the JVM pushedrecursive()function 10 times in the stack). Each times it pops the function, it goes back to theSystem.out.println(i)statement, knowing thatiwas incremented in each call, hence why you see values:That’s basically recursion in a nutshell. 🙂