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.
Let us now move the states from 4 to 6 to include the processing right after entry and the processing right before exit.
The local state1 variable is also added as a parameter to the move routine and adjusted in each place.
Here is the JavaScript code.
Here is the output of the JavaScript code.
3. More states
Finally, let us make multiple switches in the following manner.
Let us make the local variables global.
Instead of popping the values off the stack let us use the pops to restore the previous values.
When pushing values on the stack push the value of the next state after the routine would return and the current immediate state is in state2.
Here is the JavaScript code.
Here is the output of the JavaScript code.
4. Simplification
At this point, some simplifications become apparent that will now be made. These simplifications could have been made earlier, with proper insight, but will be made now.
Note that if n1 is zero then the next state is always 4 without any intervening change. This allows the case where n1 is zero to move directly from state 0 to state 4.
Below is the code with this change.
Here is the JavaScript code.
Here is the output of the JavaScript code.
5. Starting code comparison
Let us compare the above iteration code with the starting recursive code. Which code is more clear?
Here is the JavaScript code.
Here is the output of the JavaScript code.
6. Observations
The following observations can be made.
The reasoning and correctness of the original recursive code is straightforward using inductive reasoning.
The reasoning and correctness of the iterative code is not at all clear.
Explicitly managing the runtime stack makes reasoning about the code less clear.
The correctness of the iterative version follows from making invariant transformations from the original code. This is a common technique for showing that "improved" code (e.g., more machine efficient, etc.) is correct.