Got it! This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
These notes are a start at converting nontrivial recursion to iteration.
Study these notes so that when we complete the process you will be familiar with the starting point used here.
2. Recursion to iteration
A recursively defined and implemented solution is elegant and easy to reason about for correctness purposes.
However, converting recursion to iteration show how the underlying runtime stack mechanism for access to local variables works.
Below is a progressive example that shows one way how nontrivial recursion (i.e., more than one recursive call in a recursive function) can be converted to iteration.
As a starting point, below is a solution to the Towers of Hanoi problem for 3 disks (to reduce the amount of output for example purposes).
3. Starting program
Here is the JavaScript code.
Here is the output of the JavaScript code.
4. Expand code
The first step is as follows.
Expand the conditional statement for each part of the body.
Here is how this might be done. Note the following.
The variable n1 is not changed in the routine so the if statement can be broken into three parts.
Machine efficiency is not a concern at this point.
Here is the JavaScript code.
Here is the output of the JavaScript code.
5. Add states
The next step is as follows.
Convert the body of the recursive function definition to a state machine.
Here is how this might be done. Note the following.
The states go from 0 to 3. At this point, the while loop just iterates through the states in order.
Here is the JavaScript code.
Here is the output of the JavaScript code.
6. Runtime memory
Runtime memory is often divided into the following.
Runtime stack that contains a base of global variables, module variables, etc., and parameter and local variables.
Runtime heap that contains dynamically allocated and recovered variables (stings, classes, etc.).
7. Add a variable runtime stack
The next step is as follows.
Add a variable value stack (at the global level) that will replace the local variables within the recursive function. Note that the local variables include the passed parameters and any local variables in the recursive function definition.
Push actual parameters on the stack. Get these local variables from the stack. These are removed (popped) on function return. This removes the formal and actual parameters.
Here is how this might be done.
Here is the JavaScript code.