# Outline of Class 22: Recursion, Revisited

Held: Tuesday, February 24, 1998

• Don't forget that the exam is tomorrow at 8am. Any final questions?
• So, who has an idea on how to solve the "iterative logarithmic exponentiation" problem?
• Reminder: I've changed the due date for assignment 4.

## Recursion, Revisited

### Mutual Recursion

• This view of recursion has some flaws. At times, an algorithm does not directly call itself, but instead calls another which then calls the first.
• E.g, A calls B, B calls A.
• Although such algorithms are not directly recursive, they are still called recursive algorithms.
• I use the term mutually recursive to clarify what's going on.

### Tail Recursion

• Some "practical programmers" consider recursion "inefficient". Why? Because in a standard implementation of a programming language, it is necessary to put a stack frame (information on the current invocation of a function) in memory for each function call, and to remove it from memory at the completion of the function call.
• However, many programming languages can more efficiently represent tail-recursion.
• A tail-recursive algorithm does no work after any recursive call.
• Tail recursive algorithms have the form
```public returnType tailRecursiveAlgorithm(someType input, SomeType extraInfo) {
someType simpler_input;

if (baseCase(input)) {
return baseComputation(input);
}
else {
simpler_input = simplify(input);
return recursiveAlgorithm(simpler_input,more_stuff));
} // recursive case
} // tailRecursiveAlgorithm
```
• Here's a tail-recursive version of factorial (with a helper function). It uses a separate "accumulator" to gather the multiplications that we would normally have done after the recursive call.
```public int factorial(int n)
{
return factorial(n, 1);
}
public int factorial(int n, int acc)
{
if (n == 0) {
return acc;
}
else {
return factorial(n-1, acc*n);
}
} // factorial(int,int)
```

On to Recursion Repeated
Back to Design
Outlines: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
Current position in syllabus

Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.