- What are the essential features of a recursive function?
- A recursive function or procedure is defined in terms of itself, so it calls itself. It must have a base case, a way to return without making a recursive call, and a general case, where the recursive call takes place. Each call must change its state and move towards the base case.
- How do you write a recursive function from a loop?
- Replace the loop with a recursive call. Do not keep the loop inside the function, because each call would then run it again. Check the base case first and return a value from it. In the general case, return a value built from a call that has moved one step towards the base case, with every branch returning a value.
- How do you trace a recursive function with a trace table?
- A trace table gives a row to each call as it is made, and this going down is winding. At the base case the function returns without making a recursive call. Coming back up, each waiting call receives a value and finishes, and this is unwinding. The trace shows the first rows as calls not yet finished and the last rows as results returned.
- When is recursion beneficial?
- Recursion is beneficial for problems that can be broken down into smaller, repetitive problems. It helps most for problems that have many possible branches, or that are too complex for an iterative approach. Examples include calculating a factorial, a mathematical series, Fibonacci, tree traversal and the evaluation of RPN expressions.
- How does a compiler use a stack when it translates recursive code?
- The compiler must produce object code that supports the recursive calls, and that code uses a stack. With each recursive call, the object code pushes return addresses and the values of local variables onto the stack. After the base case is reached, it pops them off the stack, which is the unwinding.
- Is a recursive rewrite of a loop allowed to keep the loop inside the function?
- No. Many candidates did not produce a recursive solution, and some kept a loop within the function, which meant each call would run several times. In a recursive rewrite the recursive call does the repeating, and no loop remains in the function.