24/08/2009
1
RECURSION
Lecture 6
CS2110 – Fall 2009
2
3
Recursion Overview
4
Recursion is a powerful technique for specifying
functions, sets, and programs
Example recursively-defined functions and programs
factorial
factorial
combinations
exponentiation (raising to an integer power)
Example recursively-defined sets
grammars
expressions
data structures (lists, trees, ...)
The Factorial Function
(n!)
5
Define n! = n·(n
−
1)·(n
−
2)···3·2·1
read: “n factorial”
E.g., 3! = 3·2·1 = 6
By convention, 0! = 1
The function int
→
int that gives n! on input n is called
the
factorial function
The Factorial Function
(n!)
6
n! is the number of permutations of n distinct objects
There is just one permutation of one object.
1! = 1
There are two permutations of two objects: 2! = 2
There are two permutations of two objects:
2! = 2
1 2
2 1
There are six permutations of three objects:
3! = 6
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
If n > 0,
n! = n·(n
−
1)!

This
** preview**
has intentionally

**sections.**

*blurred***to view the full version.**

*Sign up*