Recursion Step Through

You can get a better idea of what’s going on while recursive calls are being made by stepping through a recursive program and observing the call stack in action.  Try this; write a recursive function in VB.NET to calculate the factorial of any natural number n, which is passed as a parameter when a button is pressed as shown below.

Set a break point on the function definition.  Set up a Watch window to watch the contents of n, and the return value of the function, as the program is running.  Also open the Call Stack window (as shown below).

Step through the function slowly, observing the contents of the call stack and the return value of the function as each line is executed.

nfactorial_step_through

Notice that in the line containing the recursive call, the function calls itself BEFORE any calculation is done.  The return value of a new invocation must be resolved before the multiplication can be performed.  With each successive call of the function, the multiplication operations cannot be performed immediately.  The multiplication operations are performed only when the base case has been met (when n=1), all of the calls have been made, and each invocation of the function returns control to its previous invocation.