Recursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself.
For example, we can define the operation "find your way home" as:
- Take one step toward home.
- "find your way home".
Here the solution to finding your way home is two steps (three steps). First, we don't go home if we are already home. Secondly, we do a very simple action that makes our situation simpler to solve Finally, we redo the entire algorithm.
Identify the 3 parts of the recursive algorithm:
- Base Case: if ( nargin() == 2 ) result = a + b;
- "Work toward base case": a+b becomes the first parameter. This reduces the number of parameters to the function from 3 to 2, and 2 is the base case!
- Recursive Call: add_numbers(a+b, c);
- "Work toward base case": a+b becomes the first parameter. This reduces the number of parameters to the function from 3 to 2, and 2 is the base case!
- Recursive Call: add_numbers(a+b, c);
Why Recursion Works
In a recursive algorithm, the computer "remembers" every previous state of the problem. This information is "held" by the computer on the "activation stack" (i.e., inside of each functions workspace).
Every function has its own workspace PER CALL of the function.
0 komentar:
Posting Komentar