int fact( int n ) { if( n == 0 ) return( 1 ) ; else return( n * fact( n - 1 )) ; }Let's trace the flow for a call of
fact(3)
.
n=3
.
n=0
.
n*fact(n-1)
so we
call fact()
.
n=2
.
n=0
.
n*fact(n-1)
so we
call fact()
.
n=1
.
n=0
.
n*fact(n-1)
so we
call fact()
.
n=0
.
n=0
.
fact(0)
.
fact(0)=1
we compute n*fact(n-1)
for n=1
.
fact(1)
.
fact(1)=1
we compute n*fact(n-1)
for n=2
.
fact(2)
.
fact(2)=2
we compute n*fact(n-1)
for n=3
.
fact(3)
.
Next, let's look at a recursive function for Fibonacci numbers.
int fibb( int n ) { if( n == 1 || n == 2 ) return( 1 ) ; else return( fibb( n - 1 ) + fibb( n - 2 )) ; }Notice here that we can have more than one place where a function calls itself. As an exercise, you should trace through a call of
fibb(3)
.
Consider again the function G() defined by:
g
(lower case).