18.3 Example Using Recursion: Factorials

Let’s write a recursive program to perform a popular mathematical calculation. Consider the factorial of a positive integer n, written n! (pronounced “n factorial”), which is the product

n(n1)(n2)1

with 1! equal to 1 and 0! defined to be 1. For example, 5! is the product 54321, which is equal to 120.

The factorial of integer number (where number 0) can be calculated iteratively (non-recursively) using a for statement as follows:

factorial = 1;
for (int counter = number; counter >= 1; counter--) {
   factorial *= counter;
}

A recursive declaration of the factorial calculation for integers greater than 1 is arrived at by observing the following relationship:

n!=n(n1)!

For example, 5! is clearly ...

Get Java How to Program, Early Objects, 11th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.