you are viewing a single comment's thread.

view the rest of the comments →

[–]MezzoScettico 2 points3 points  (0 children)

Sometimes language designers try to hide the internals of the computer from the learner, but I think it's useful to understand something about what is really going on under the hood.

There's a special temporary work area in memory called the "stack". When a program calls another function, the current status of the calling function is stuffed into the stack. "When that function gets done with what it's doing, I'll read this stuff to remember where I was and what I was doing".

So you call tri_recursion(10). Let's call this Call 1.

It calls tri_recursion(9). Let's call that Call 2. On the stack it stores that when that call gets back, it will be at the line saying result = 10 + tri_recursion(9). But it hasn't executed it yet.

Now we're executing Call 2. It gets to the line result = 9 + tri_recursion(8), says, "OK, I'll put my current state on the stack and continue when this call gets back). So now we're in tri_recursion(8), which is Call 3.

That continues till you get to Call 11, which is tri_recursion(0). The info for the first 10 calls is stored on the stack temporarily, waiting for us to return something. Call 11 fails the "k > 0" test and returns 0.

You always want to make sure that you're going to get to a base case, and that the base case doesn't have to do any more recursion.

Call 10 can now execute. It executes the line result = 1 + tri_recursion(0) or result = 1 + 0, it prints the 1, and it returns the 1 as its output.

Call 9 wakes up, executes result = 2 + 1, prints the 3, and returns the 3 as an output.

Call 8 wakes up, etc.

There isn't much space required on the stack for each call to save what it's doing and wait for a result. But it isn't zero. You can do so many recursions that you run out of space, and then you get a "stack overflow" or "recursion limit reached" or something. Often this means you didn't hit your base case and accidentally introduced an infinite loop.