The Department of Computer Science & Engineering
 STUART C. SHAPIRO: CSE 116 B

# Recursion

Riley, Chapter O6

Introduction
According to a theorem proved by Corrado Böhm and Giuseppe Jacopini (CACM, 1966), every procedure can be expressed with just the control structures:
1. Sequence: Do one action, and then another, and then another, etc.
2. Selection: Do one action or another, based on some condition.
3. Loop: Repeatedly do an action as long as some condition holds.
You already know about sequence, selection, and iterative loops (for and while). Another kind of looping control is called recursion.

Recursion solves a problem by solving successively smaller instances of the same problem.

"A journey of 1,000 miles begins with a single step."
```      To journey n miles:
If n <= 0
Stop.
Else
Take 1 step.
Journey n miles - 1 the length of 1 step.
Stop.
```

A useful numerical algorithm:
```      To determine if the integer n is divisible by 3:
If n < 10
If n = 0, 3, 6, or 9, "yes".
Else "no".
Else
Let m be the sum of the digits of n.
If m is divisible by 3, "yes".
Else "no".
```

Example: 85927? Sum digits = 31. Sum digits = 4. No.
Example: 20487? Sum digits = 21. Sum digits = 3. Yes.

An in-class exercise based on Carrano & Savitch, Data Structures and Abstractions with Java.
```      To count down from n, as asked by person p:
Say (loudly) n.
If n > 0
Ask (loudly) a neighbor to count down from n-1.
Wait for that neighbor to tell you "Done".
Say (loudly) to p, "Done".
```
```      To count up to n, as asked by person p:
If n > 0
Ask (loudly) a neighbor to count up to n-1.
Wait for that neighbor to tell you "Done".
Say (loudly) n.
Say (loudly) to p, "Done".

```

Towers of Hanoi
There are 3 posts. On one is some disks of different sizes, largest on bottom, smallest on top. You must move them to another post, moving one at a time, never putting a disk on a smaller disk.
```      To move n disks from starting post, s, to destination post, d, using intermediate post, i:
If n = 1
Move the disk from s to d.
Else
Move n-1 disks from s to i using d.
Move 1 disk from s to d.
Move n-1 disks from i to d using s.
```
Try it

The pattern:
1. Base case: If the problem can be solved immediately, do so.
2. Recursive case: Solve the problem using a solution of a simpler instance (one closer to the base case).
If every case is correct, and the recursive case brings you closer to the base case, the algorithm is correct.

Backtrack Search
Try MazeGrid