Lecture 4/22: Introduction to Recursion


April 22, 2020

đź“‚Associated files

Introduction to Recursion

CS 106B: Programming Abstractions

Spring 2020, Stanford University Computer Science Department

Lecturers: Chris Gregg and Julie Zelenski

Recursion recursion recursion...


Slide 2

Announcements


Slide 3

A Little Demo


Slide 4

Towers of Hanoi


Slide 5

What is Recursion?

Google page when you search for recursion -- Google asks, 'Did you mean: recursion?'


Slide 6

Why Recursion?

  1. Great style
  2. Powerful tool
  3. Master of control flow

Slide 7

Recursion in Programming


Slide 8

Recursion in Real Life

A jigsaw puzzle that is very, very hard to complete (Ridiculously hard puzzle)


Slide 9

Counting a column of people


Slide 10

Counting a column of people recursively in C++

int numPeopleInLine(Person curr) {
    if (noOneBehind(curr)) {
        return 1;
    } else {
        Person personBehind = curr.getBehind();
        return numPeopleInLine(personBehind) + 1; // recursive call!
    }
}

Slide 11

Recursive Structure


Slide 12

Recursive Functions

int numPeopleInLine(Person curr) {
    // base case
    if (noOneBehind(curr)) {
        return 1;
    } else {
        // recursive case
        Person personBehind = curr.getBehind();
        return numPeopleInLine(personBehind) + 1; // recursive call!
    }
}

Slide 13

The Three "Musts" of Recursion

  1. Your code must have a case for all valid inputs.
  2. You must have a base case that makes not recursive calls.
  3. When you make a recursive call it should be to a simpler instance of the same problem, and make forward progress towards the base case.

Slide 14

The "Recursive Leap of Faith"

A picture of a woman leaping into the water in a 'leap of faith'


Slide 15

Simple Recursion Examples


Slide 16

Let's code power(x, n)

The Qt Creator logo


Slide 17

The power(x, n) function

int power(int x, int n) {
    if (n == 0) {
        return 1;
    } else {
        return x * power(x, n - 1);
    }
}

Slide 18

Big O of power(x, n)?


Slide 19

Faster power function!


Slide 20

Mystery Recursion: Trace this function

The words 'Code Mystery' with a fingerprint

int mystery(int n) {
    if (n < 10) {
        return n;
    } else {
        int a = n / 10;
        int b = n % 10;
        return mystery(a + b);
    }
}

Slide 21

More examples! isPalindrome(string s)


Slide 22

Remember: The Three "Musts" of Recursion

  1. Your code must have a case for all valid inputs.
  2. You must have a base case that makes not recursive calls.
  3. When you make a recursive call it should be to a simpler instance of the same problem, and make forward progress towards the base case.

Slide 23

isPalindrome

// Returns true if the given string reads the same
// forwards as backwards.
// Trivially true for empty or 1-letter strings.
bool isPalindrome(const string& s) {
    if (s.length() < 2) { // base case
        return true;
    } else { // recursive case
        if (s[0] != s[s.length() - 1]) {
            return false;
        }
        string middle = s.substr(1, s.length() - 2);
        return isPalindrome(middle);
    }
}

Slide 24

Back to the Towers of Hanoi

The Towers of Hanoi, thinking about a solution. We need to (eventually) get the bottom, largest disc on pole A to the bottom of pole C


The Towers of Hanoi: If we (somehow) get all the other discs from A to B with only the largest disc remaining on pole A, we can directly move the largest disc from pole A to pole C


The Towers of Hanoi: (same as above) If we (somehow) get all the other discs from A to B with only the largest disc remaining on pole A, we can directly move the largest disc from pole A to pole C


The Towers of Hanoi: Because we are trying to get the largest disc on pole A (on the bottom) to pole C, we must first get the second-largest disc to pole B


The Towers of Hanoi: if we are trying to get the second-largest disc from pole A to pole B, then we must first get all the smaller discs to pole C


The Towers of Hanoi: If we do get the smaller discs than the second-largest disc to pole C, we can directly move the second-smallest disc from pole A to pole B


The Towers of Hanoi



The Towers of Hanoi: original puzzle with all five discs on pole A


The Towers of Hanoi: Step 1: move the four smaller discs from pole A to Pole B


The Towers of Hanoi: Step 2: Now that the fours amller discs are on pole B, we can move the largest disc from pole A to pole C


The Towers of Hanoi: Step 3: Now that the four smaller discs are on pole B, move them from pole B to pole C


The Towers of Hanoi: Repeat steps 1-3 at each stage!


Slide 25

Recursion Recap