1. Recursion
1. Recursion
• Each recursive algorithm must have at least one base case, as well
as the general case (recursive)
Recursion: General Format (Common)
if (some known condition) // base case
return base value (or void)
// general case
recursive function call
return general case value
• Each recursive algorithm must have at least one base case, as well
as the general case (recursive)
Recursion: Factorial
• 3! = 3 × 2! = 3 × 2 × 1! = 3 × 2 × 1
• fact(3) = 3 * fact(2) = 3 * 2 * fact(1) = 3 * 2 * 1
int fact(int N) {
if (N == 0)
return 1;
return N*fact(N-1);
}
----------------
cout << fact(3);
Factorial: Step-by-Step
int fact(3) int fact(3)
if(3 == 1)(False) if(3 == 1)(False)
… …
return 3*fact(2); return 3*2;
int fact(1)
if (1 == 1)(True)
return 1;
…
Fibonacci Numbers
• Sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …
• F1 = 1, F2 = 1
• FN = FN - 1 + FN - 2
Fibonacci Numbers
Fibonacci Numbers: Recursion Performance
• Problem statement
– Beginning with n disks on pole A and zero disks on poles B and C, solve
towers(n, source, destination, auxiliary) .
Tower of Hanoi: Two Disks
Src Aux Dst
Src Dst Aux
What if 𝒏 = 𝟏?
Towers of Hanoi: Pseudocode
Base Case
General Case
Tower of Hanoi: Three Disks Tracing
30
Tower of Hanoi: C++ Code
Tail Recursion
• If the recursive call appears as the last step in the function, then it
can be converted to iterative.
• Is this tail recursion?
void foo(int x) {
cout << x;
foo(x+1);
}
----------------
foo(1);
Tail Recursion
• If the recursive call appears as the last step in the function, then it
can be converted to iterative.
• Is this tail recursion?
int fact(int N) {
if (N == 0)
return 1;
return N*fact(N-1);
}
----------------
cout << fact(3);
Tail Recursion
• If the recursive call appears as the last step in the function, then it
can be converted to iterative.
• Is this tail recursion?
Tail Recursion
• If the recursive call appears as the last step in the function, then it
can be converted to iterative.
• Is this tail recursion?