An activation record usually contains:
- Values for all parameters to the function, location of the first cell in an array is passed or a variable is passed by reference, and copes of all other data.
- Local (automatic) variables that can be stored elsewhere, in which case, the activation record contains only their descriptors and pointers to the locations where they are stored.
- The return address to resume control by the caller, the address of the caller’s instruction immediately following the call.
- The returned value for a function not declared as a void.
Advantages of using recursion:
- Similarity to the original definition.
- Increases the program readability.
- Improves self-documentation.
- Simplifies coding.
- Shorter than iterative implementations.
Tail recursion is characterized by the use of only one recursive call at the very end statement left to be executed by the function; the recursive call is not only the last statement but there are no earlier recursive calls, direct or indirect.
Tail recursion is more suitable for language like Prolog that has no explicit loop construct.
Consider the following functions:
top = 0;
while(stack[top] != ‘\n’)
for (top -=2; top >= 0; cout.put(stack[top–]));
while(ch != ‘\n’)
After comparing function1 to function2, we can conclude that the first version is better because it is faster, no function calls are made, and the function is self-sufficient, whereas, function2 calls at least one function during each loop iteration, slowing down execution.
Indirect recursion is defined as, when a function call itself indirectly. As example:
- Function f() will call function g()
- Function g() is going to call function f() again.
A more complicated case of recursion is found in definition in which a function is not only defined in terms of itself, but also as one of the parameters. This is called Nested Recursion.
If you traced a usual funtion that computes Fibonacci Numbers, you’ll observe that it repeats computation of some numbers. As indicated using recursion Fib(n), number of computations equals to 2 . Fib(n + 1) – 1.
A better solution is done by using the equation: Fib(n) = dn/root(5) where d = 1/2 +(1 + root(5)). This is coded as:
deMoivreFib(unsigned int n)
return ceil(exp(n*log(1.6180339897) – log(2.2360697995)) – .5);
Download solutions for this chapter from this link