Theory Recursion – Why Does Recursion Return the First Call in the Stack and Not the Last?

recursiontheory

I cant for the life of me figure out why this returns 0 rather than 5. i keeps getting incremented before it hits the last return statement, however it always returns 0, from the first call in the stack. I would think that since the most recent call on the stack hits the return in the block i == 5 first it would return and print 5.

Returns 0

public static void main(String[] args) {
    System.out.println(incrementI(0));
}       


public static int incrementI(int i) {
    if (i == 5){
        return i;           
    } else {
         incrementI(i + 1);
    }
    return i;  
}

Returns 5

public static int incrementI(int i) {
    if (i == 5){
        return i;           
    } else {
        return incrementI(i + 1);
    }               
}

I'm not looking for a code fix, but rather an explanation to why recursion works this way.

Best Answer

The key here is stack frames. Lets take a look at your first example:

public static int incrementI(int i) {
    if (i == 5){
        return i;           
    } else {
         incrementI(i + 1);
    }
    return i;  
}

On the first call, you have a variable named i, with the value of 0. Since i isn't 5, its going to call incrementI again with 1.

This time around, you have a new stack frame, and a different variable named i. Every time you call incrementI, a brand new i is being created with the new value.

When you've called incrementI 6 times, each function call has its own copy of i:

 incrementI: 5
 incrementI: 4
 incrementI: 3
 incrementI: 2
 incrementI: 1
 incrementI: 0

The top function returns 5 (as that is i), and then the next function returns 4 (as that is its copy of i), until the bottom function returns 0.

In your second example, the same thing occurs, except each function is returning what the above function returned. Therefore, the top function returns 5, then the next function returns 5 (as that is what the previous function returned), and so on.

Related Topic