DS Lecture 14 Recursion
DS Lecture 14 Recursion
5 November 2024 1
Recursion (3.5)
⚫ In some problems, it may be natural to define
the problem in terms of the problem itself.
⚫ Recursion is useful for problems that can be
represented by a simpler version of the same
problem.
⚫ Example: the factorial function
6! = 6 * 5 * 4 * 3 * 2 * 1
We could write:
6! = 6 * 5!
2
Recursion (cont.)
⚫ Recursion is one way to decompose a task into
smaller subtasks. At least one of the subtasks is
a smaller example of the same task.
5
Visualizing Recursion
Example recursion trace:
Recursion trace
return 4*6 = 24 final answer
⚫ A box for each call
recursiveFactorial(4)
recursive call call return 3*2 = 6
6
factorial function
8
A Word of Caution
⚫ To trace recursion, function calls operate as a stack –
the new function is put on top of the caller.
⚫ We have to pay a price for recursion:
calling a function consumes more time and
memory than adjusting a loop counter.
high performance applications (graphic action
games, simulations of nuclear explosions) hardly
ever use recursion.
⚫ In less demanding applications, recursion is an
attractive alternative for iteration (for the right
problems!)
9
Infinite Loops
If we use iteration, we must be careful not to create an
infinite loop by accident.
12
Direct Computation Method
⚫Fibonacci numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
where each number is the sum of the
preceding two.
⚫Recursive definition:
F(0) = 0;
F(1) = 1;
F(number) = F(number-1)+ F(number-
2);
Example 2: Fibonacci numbers
//Calculate Fibonacci numbers using recursive function.
//A very inefficient way, but illustrates recursion well
int fib(int number)
{
if (number == 0) return 0;
if (number == 1) return 1;
return (fib(number-1) + fib(number-2));
}
int fib(int n)
{
int f[100];
f[0] = 0; f[1] = 1;
for (int i=2; i<= n; i++)
f[i] = f[i-1] + f[i-2];
return f[n];
}