# CS156 Recursion

A Sierpinski gasket is three half-sized Sierpinski gaskets arranged in a triangle.

# Recursion

• In C it is legal for functions to call themselves. This is known as recursion.
• Some computations lend themselves naturally to recursive implementations.
• Recursive functions should
• simplify the implementation of a solution
• have a base case
• be used sparingly

# Fibonacci sequence

 n F(n) 1 2 3 4 5 6 7 8 9 10 1 1 2 3 5 8 13 21 34 55
```           ⎧ 1		       if n≤2
F(n) = ⎨
⎩ F(n-1) + F(n-2)   otherwise
```

# Fibonacci sequence

```    fib(5)
=                   fib(4)       +        fib(3)
= [      fib(3)       + fib(2) ] + [ fib(2) + fib(1) ]
= [ fib(2) + fib(1) ] +   1      +     1    +   1
=     1    +   1      +   1      +     1    +   1
= 5
```

# Fibonacci sequence

```    int fib(int which) {
if (which <= 2)		// base case?
return 1;
return fib(which - 1) + fib(which - 2);
}
```

At any point, there can be several calls to `fib` active. The computer keeps track of them.

# Recursion: factorial

• How many ways are there to arrange:
• one card: J (1)
• two cards: JQ QJ (2×1 = 2)
• three cards: JQK JKQ QJK QKJ KJQ KQJ (3×2×1 = 6)
• four cards: … (4×3×2×1 = 24)
• In general, there are n × (n-1) × (n-2) × … × 3 × 2 × 1 ways to arrange n cards.
• This function is called factorial: n!
• 1! = 1
• n! = n × (n-1)!

# Recursion: factorial

```    int factorial(int n) {
if (n <= 1)
return 1;
return n * factorial(n-1);
}
```
• The function divides the input into two cases.
• `n` ≤ 1 : return 1
• `n` > 1 : return `n*factorial(n-1)`
• Since we are subtracting 1 from `n` at each successive call to factorial the recursion will stop when `n` becomes 1.

# The factorial Example Continued

• Take factorial(4) for example:
• factorial(4) → return 4*factorial(3)
• factorial(3) → return 3*factorial(2)
• factorial(2) → return 2*factorial(1)
• factorial(1) → return 1
• factorial(2) → return 2*1 → return 2
• factorial(3) → return 3*2 → return 6
• factorial(4) → return 4*6 → return 24

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-03-02T11:42

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA