# Recursion - PowerPoint PPT Presentation

PPT – Recursion PowerPoint presentation | free to download - id: 6c52f7-MGJlZ

The Adobe Flash plugin is needed to view this content

Get the plugin now

View by Category
Title:

## Recursion

Description:

### Reading Chapter 10 Recursion The process of solving a problem by reducing it to smaller versions of itself Example: Sierpinski s Triangle Recursive algorithm An ... – PowerPoint PPT presentation

Number of Views:15
Avg rating:3.0/5.0
Slides: 11
Provided by: Mahmo
Category:
Tags:
Transcript and Presenter's Notes

Title: Recursion

1
Recursion

2
Recursion
• The process of solving a problem by reducing it
to smaller versions of itself
• Example Sierpinskis Triangle

3
Recursive algorithm
• An algorithm is called recursive if it solves a
problem by reducing the problem to smaller
versions of itself
• A recursive algorithm can be implemented using a
recursive function

4
Recursive function
• A function that calls itself
• What is the danger?
• we need to avoid infinite recursion
• A recursive function must have
• recursive call(s) to the function with a smaller
instance of the problem
• one or more base cases to stop recursion

5
Finding a recursive solution
• A recursive solution to a problem must be written
carefully
• The idea is for each successive recursive call to
take us one step closer to the base case (a
situation in which the problem can easily be
solved)

6
General format formany recursive functions
• if (some easily-solved condition) // base case
• solution statement(s)
• else // general case
• recursive function call(s)

7
Example
• Write a recursive function Fact() to find the
factorial of n.
• What should Fact(4) return?
• What can be a good base case that represents an
easily-solved situation?
• What can be a good general case that takes us
closer to the base case?

8
Example
• int Fact (int n)
• if (n 1) // base case
• return 1
• else // general case
• return n Fact(n-1)
• // this is an example of tail recursion

9
Example Trace of calls
Returns 4 Fact(3) 4 6 24
Call 1 Fact(4)
n 4
Returns 3 Fact(2) 3 2 6
Call 2 Fact(3)
n 3
Returns 2 Fact(1) 2 1 2
Call 3 Fact(2)
n 2
n 1 Returns 1
Call 4 Fact(1)
n 1
10
Iteration or Recursion?
• Key factors
• nature of the problem
• efficiency
• Every recursive call has its own set of
parameters and local variables
• time and space overhead associated with executing
a recursive function
• Certain problems are inherently recursive and a
recursive solution is the most natural one