CS 1124 — Object Oriented Programming

Recursion

To understand recursion, first you must understand recursion.

A function that calls itself is a recursive function.  This programming technique is called recursion.  Some uses of recursion may lead to very inefficient code, while others are perfectly reasonable and make the implementation of an algorithm easier to understand.

Design

  1. Think about how you can solve the problem by using the same function on a smaller version of the problem.
  2. Do some small piece of the task at each call to the function.
  3. Know when to stop.
  4. Be sure to get the right ordering between items 1 & 2.

Always try your solution out on a small test case.  Employing such sanity checks should be an ingrained habit.

Recursive solutions are often a little surprising the first time you see them.  Practice helps.

Simple Examples

Harder Examples

Tower of Hannoi

Home


Maintained by John Sterling (jsterling@poly.edu). Last updated January 23, 2011