[Solved] Why does recursion return the first call in the stack and not the last?


Imagine you wrote such function:

public static int square(int x) {
    pow(x, 2);
    return x;
}

It will compute the square of x. But then computed square will not affect anything and the function will return just x.

Now look carefully at your code

if (i == 5){
    return i;           
} else {
    something(i + 1);
}
return i;

If i is not 5, something(i + 1) will be called. Then it will return some value but this value will not affect to anything. And then incrementI function will return just i, in your case it’s 0.

2

solved Why does recursion return the first call in the stack and not the last?