Some Dos and Don'ts About Homework

Recursion

Recursion is the defining and solving of a problem in terms of smaller instances of the same problem.

Example: Sierpinsky Gasket

Fractal:  1  1   <--- 1 bit symbolizes a pixel turned on
          0  1   <--- 0 bit symbolizes a pixel turned off
See sierpinskyColor.cpp Demo

Example: factorial

Recall:
n! = n * (n - 1) * (n - 2) * ... * 2 * 1
See factIterative.cpp Demo

Observe that that (n - 1) * (n - 2) * ... * 2 * 1 is just (n-1)!. So, we can rewrite our definition of n! as
n! = 1 if n = 0 (the base case),
n! = n * (n-1)! if n >= 1 (the recursive case).
See factRecursive.cpp Demo

How it works

Each recursive call causes a fresh copy of the stack frame for the function. An example stack of the factorial function for n = 3 is given below:

For each call to factorial a new stack frame is pushed onto the program stack. This occurs until our base case is met, namely when n is 0. Once our base case is reached, we return until we reach our original function main(), where the return value is 6 and is the answer to our original call of factorial(3).

Infinite Recursion

Infinte recursion occurs when you never hit the base case. When the base case is never reached the computer continually pushes new stack frames onto its stack until it runs out of memory. When this occurs you either crash the machine or get a fault which will halt the execution of the runaway program.

Thinking Recursively

Recursion is really based on mathematical induction. Induction works in the following way. Suppose we want to show that something works for all nonnegative integers.

For factorial:

Another example: Fibonacci Numbers

See fibonacci.cpp Demo

Example: Reversing a Sentence

We can reverse a sentence using recursion also.

See reverse.cpp Demo

To Index Previous Next