What is Recursion?

Computer Science
  • Study Guide
Summary

What is Recursion?

Summary What is Recursion?

Recursion turns out to be a wonderful technique for dealing with many interesting problems. Solutions written recursively are often simple. Recursive solutions are also often much easier to conceive of and code than their iterative counterparts.

What kinds of problems are well solved with recursion? In general, problems that are defined in terms of themselves are good candidates for recursive techniques. The standard example used by many computer science textbooks is the factorial function.

The factorial function, often denoted as n!, describes the operation of multiplying a number by all the positive integers smaller than it. For example, 5! = 5*4*3*2*1. And 9! = 9*8*7*6*5*4*3*2*1.

Take a good close look at the above, and you may notice something interesting. 5! can be written much more concisely as 5! = 5*4!.

Figure %: 5! = 5*4*3*2*1 = 5*4!

And 4! is actually 4*3!.

Figure %: 4! = 4*3*2*1 = 4*3!

We now see why factorial is often the introductory example for recursion: the factorial function is recursive, it is defined in terms of itself. Taking the factorial of n, n! = n*(n - 1)! where n > 0.