Slides 11
Slides 11
Slides 11
Ali Kassem
Presentation slides are copyright 2002 by John Lewis and William Loftus. All rights reserved.
Instructors using the textbook may use and modify these slides for pedagogical purposes.
Recursion
Recursion is a fundamental programming technique that
can provide elegant solutions certain kinds of problems
Ali Kassem 2
Recursive Thinking
Recursion is a programming technique in which a method
can call itself to solve a problem
Ali Kassem 3
Recursive Definitions
Consider the following list of numbers:
A LIST is a: number
or a: number comma LIST
Ali Kassem 4
Recursive Definitions
The recursive part of the LIST definition is used several
times, ultimately terminating with the non-recursive part:
number
37
Ali Kassem 5
Infinite Recursion
All recursive definitions must have a non-recursive part
Ali Kassem 6
Recursive Definitions
Mathematical formulas often are expressed recursively
1! = 1
N! = N * (N-1)!
120
5!
24
5 * 4!
4 * 3! 6
3 * 2!
2
2 * 1!
1
Ali Kassem 8
Recursive Programming
A method in Java can invoke itself; if set up that way, it is
called a recursive method
Ali Kassem 9
Recursive Programming
Consider the problem of computing the sum of all the
numbers between 1 and any positive integer N, inclusive
N N-1 N-2
= N + = N + (N-1) +
i=1 i=1 i=1
= etc.
Ali Kassem 10
Recursive Programming
result = 6
main
sum(3)
result = 3
sum
sum(2)
result = 1
sum
sum(1)
sum
Ali Kassem 12
Recursion vs. Iteration
Just because we can use recursion to solve a problem,
doesn't mean we should
Ali Kassem 13
Recursion vs. Iteration
Every recursive solution has a corresponding iterative
solution
m1 m2 m3
m1 m2 m3
m1 m2 m3
Ali Kassem 16
Maze Traversal
We can use recursion to find a path through a maze; a path
can be found from any location if a path can be found from
any of the location’s neighboring locations
The goal is to move all of the disks from one peg to another
according to the following rules:
• We can move only one disk at a time
• We cannot place a larger disk on top of a smaller disk
• All disks must be on some peg except for the disk in transit between
pegs
Towers of Hanoi
(Figure 11.5 here)
Towers of Hanoi
A solution to the three-disk Towers of Hanoi puzzle
The base case is reached when the area for the “remaining”
tile shrinks to a certain size
Ali Kassem 28
TiledPictures.java
Fractals
A fractal is a geometric shape than can consist of the same
pattern repeated in different scales and orientations