Recursion in C, C++
Recursion in C, C++
Fibonacci Numbers
/* Returns nth fibonacci number fn for n >= 0:
- fn = fn-1 + fn-2
- Base case f0 = 0 and f1 = 1 */
A B C D
passes program
control (flow)
returns program
control (flow)
int factorial(int n) {
if (n < 2) return 1;
else return factorial(n-1) * n;
factorial(3): }
factorial (2)
factorial (1)
2
1
3
Value returned
Implementation of recursive calls
Both the recursive and the iterative routines take time which is
proportional to n, but the iterative algorithm will be much
faster in most language implementations. However, the
recursive is usually more efficient to code!
Combinatorial explosion in Fibonacci
if (n == 0) return fib0;
else if (n == 1) return fib1;
return fib1;
}
Choosing recursion
A B C
Some initial steps
A B C
A B C
Breaking the goal into subgoals
A B C
A B C
Implementation of Towers of Hanoi
/*
* Prints sequence of moves to move n disks (n >= 0)
* from peg source to peg dest using peg inter
* as intermediate.
*/
void move(int n, char source, char dest, char inter) {
if (n > 0) {
move(n - 1, source, inter, dest);
printf(“Move disk from peg %c to peg %c\n”,
source, dest);
move(n - 1, inter, dest, source);
} /* Otherwise n == 0, so do nothing */
}
The moves: A to C, A to B, C to B, A to C, B to A, B to C, A to C.
Tail recursion
A recursive function is called tail recursive if it only calls itself
as a final operation:
void f(int a, int b) {
int c, d;
if (<some_condition>) { /* Not real C */
/* some statements */
f(c, d); /* end with a recursive call */
} else { /* handle base case */ }
}