0% found this document useful (0 votes)
8 views

2 - Recursion

Uploaded by

Muhammad Fahad
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

2 - Recursion

Uploaded by

Muhammad Fahad
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Recursion

• Recursive functions
– Functions that call themselves
– Can only solve a base case
– Divide a problem up into
• What it can do
• What it cannot do
– What it cannot do resembles original problem
– The function launches a new copy of itself (recursion step) to solve
what it cannot do
– Eventually base case gets solved
• Gets plugged in, works its way up and solves whole problem
Example Using Recursion:
Factorial
• Example: factorials
– 5! = 5 * 4 * 3 * 2 * 1
– Notice that
• 5! = 5 * 4!
• 4! = 4 * 3! ...

– Can compute factorials recursively


– Solve base case (1! = 0! = 1) then plug in
• 2! = 2 * 1! = 2 * 1 = 2;
• 3! = 3 * 2! = 3 * 2 = 6;
Factorial
Factorial (n)
1. if n=1
2. return 1
3. else
4. return n * Factorial(n-1)
120
Call Sequence
Factorial ( 5 )
if 5 = 1
return 1
else
24
return 5 * Factorial (4)

Factorial ( 4 )
if 4 = 1
return 1
else
return 4
6
* Factorial (3)

Factorial ( 3 )
if 3 = 1
return 1
else
return 3 *
2
Factorial (2)

Factorial ( 2 )
if 2 = 1
return 1
else
1
return 2 * Factorial (1)

Factorial ( 1 )
if 1 = 1
return 1
else
return 5 * Factorial (4)
Example Using Recursion: The Fibonacci
Series
• Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
– Each number is the sum of the previous two
– Can be solved recursively:
• Fib( n ) = Fib( n - 1 ) + Fib( n – 2 )
– Code for the Fibonacci function

Fibonnaci (n)
1. if n ≤ 2
2. return n-1
3. else
4. return Fibonnaci (n-1) + Fibonacci (n-2)
Is it correct?

Fibonnaci (n)
1. if n =1 or n = 2
2. return n-1
3. else
4. return Fibonnaci (n-1) + Fibonacci (n-2)

Fib(n) = Fib(n-1) + Fib(n-2)


3

Fib ( 5 )
if 5 = 1 or 5 = 2
return 5-1
else return Fib (4) + Fib (3)
2 1

Fib ( 4 ) Fib ( 3 )
if 4 = 1 or 4 = 2 if 3 = 1 or 3 = 2
return 4-1 return 3-1
else return Fib (3) + Fib (2) else return Fib (2) + Fib (1)
1 1 1 0

Fib ( 3 ) Fib ( 2 ) Fib ( 2 ) Fib ( 1 )


if 3 = 1 or 3 = 2 if 2 = 1 or 2 = 2 if 2 = 1 or 2 = 2 if 1 = 1 or 1 = 2
return 3-1 return 2-1 return 2-1 return 1-1
else return Fib (2) + Fib (1) else return Fib (1) + Fib (0) else return Fib (1) + Fib (0) else return Fib (0) + Fib (-1)
1 0

Fib ( 2 ) Fib ( 1 )
if 2 = 1 or 2 = 2 if 1 = 1 or 1 = 2
return 2-1 return 1-1
else return Fib (1) + Fib (0) else return Fib (0) + Fib (-1)
Recursion vs. Iteration
• Repetition
– Iteration: explicit loop
– Recursion: repeated function calls
• Termination
– Iteration: loop condition fails
– Recursion: base case recognized
• Both can have infinite loops
• Balance
– Choice between performance (iteration) and good
software engineering (recursion)

You might also like