Recursion
Chapter 17
17
What is recursion?
Recursion occurs when a method calls
itself, either directly or indirectly.
Used to solve difficult, repetitive
problems
17
Factorial Example
N! (N Factorial)
N! = N * (N – 1)! for N >= 0 and 0! = 1
5! = 5 * 4! or 5 * 4 * 3 * 2 * 1 * 1 = 120
4! = 4 * 3! or 4 * 3 * 2 * 1 * 1 = 24
3! = 3 * 2! or 3 * 2 * 1 * 1 = 6
2! = 2 * 1! or 2 * 1 * 1 = 2
1! = 1 * 0! or 1 * 1 = 1
0! = 1
17
Calculate Factorials Using Recursion
The Java solution:
private int doFactorial(int N)
{
if ( N == 0 )
{
return 1;
}
return N * doFactorial(N – 1);
}
17
Towers of Hanoi
Three towers hold rings stacked in order
from largest to smallest (bottom to top)
Player can only move one ring at a time
Larger rings cannot be stacked on top of
smaller ring
Player must move stack to another tower
17
The Towers of Hanoi Algorithm
Classic problem can be solved with
recursion.
Move N–1 rings to storage tower
Move Nth ring to destination tower
Move N–1 rings to destination tower
17
Towers of Hanoi Solution
Final graphical solution includes the files:
TowerRing.java
Tower.java
TowerMove.java
ThreeTowers.java
TowersOfHanoi.java
TowerPanel.java
17
Graphical Towers of Hanoi
Applet in progress

Chapter 17

  • 1.
  • 2.
    17 What is recursion? Recursionoccurs when a method calls itself, either directly or indirectly. Used to solve difficult, repetitive problems
  • 3.
    17 Factorial Example N! (NFactorial) N! = N * (N – 1)! for N >= 0 and 0! = 1 5! = 5 * 4! or 5 * 4 * 3 * 2 * 1 * 1 = 120 4! = 4 * 3! or 4 * 3 * 2 * 1 * 1 = 24 3! = 3 * 2! or 3 * 2 * 1 * 1 = 6 2! = 2 * 1! or 2 * 1 * 1 = 2 1! = 1 * 0! or 1 * 1 = 1 0! = 1
  • 4.
    17 Calculate Factorials UsingRecursion The Java solution: private int doFactorial(int N) { if ( N == 0 ) { return 1; } return N * doFactorial(N – 1); }
  • 5.
    17 Towers of Hanoi Threetowers hold rings stacked in order from largest to smallest (bottom to top) Player can only move one ring at a time Larger rings cannot be stacked on top of smaller ring Player must move stack to another tower
  • 6.
    17 The Towers ofHanoi Algorithm Classic problem can be solved with recursion. Move N–1 rings to storage tower Move Nth ring to destination tower Move N–1 rings to destination tower
  • 7.
    17 Towers of HanoiSolution Final graphical solution includes the files: TowerRing.java Tower.java TowerMove.java ThreeTowers.java TowersOfHanoi.java TowerPanel.java
  • 8.
    17 Graphical Towers ofHanoi Applet in progress