CS156: Intro to C, Part I

Spring 2018

Recursion

See this page as a slide show

CS156 Recursion

Sierpinski Gasket

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

Recursion

Fibonacci sequence

n12345678910
F(n)11235813213455
           ⎧ 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

Recursion: factorial

    int factorial(int n) {
   	if (n <= 1)
        	return 1;
        return n * factorial(n-1);
    }

The factorial Example Continued

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
© 2018 Colorado State University
CS Building