[   ^ to index...   |   <-- previous   |   next -->   ]

Using recursion

The general formula for defining recursive functions, data structures, etc. is as follows:

  1. Define a base case for the recursion. Most often this will be zero, one, the empty list/tree/node, or something similar.

  2. Define the inductive case (or cases) that "shrinks" all other cases towards the base case.

Recursive procedures: addition

It is traditional to introduce recursion with something extremely simple, like factorial. Well, here's something even simpler than factorial:

int add(int x, int y) { if (x == 0) return y; // base case else return 1 + add(x-1, y); // inductive case }

Notice that the inductive case, by subtracting 1 from x, "shrinks" all integers down to 0, which is the base case.

Recursive data: linked lists

A linked list is either the empty list (NULL) or a node containing an element and a pointer to another list:

struct Node { int element; Node * next; };

Exercise

How would we sum the elements in a linked list of the above type iteratively? Recursively?

// SOLUTION: to be presented next week

Last modified: Thu Jul 6 13:54:48 PDT 2000