...

/

Recursion and Memory Visualization

Recursion and Memory Visualization

This lesson will discuss how recursive methods use the stack.

Memory allocation to methods

When a method is called, the state of the method is placed on the call stack along with the information about where it was called from. This tells the run-time where it should return to when the current method finishes executing. Each recursive call pushes a new stack frame. A stack frame consists of information such as the return address, argument variables, and local variables related to that method call.

When a method calls itself, the new method call gets added to the top of the call stack and execution of the current method pauses while the recursive call is being processed. When the base case is reached the stack frames start popping from the stack until the stack becomes empty.

Example

Computing Factorials

What is a Factorial?

A factorial is the product of an integer and all the positive integers below it. It is denoted by the symbol: !!

For example, 4! (read as four factorial) is denoted as follows:

4!=4×3×2×1= ...