15.3. Example Using Recursion: Factorials

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

n · (n – 1) · (n – 2) · ... · 1

with 1! equal to 1 and 0! defined to be 1. For example, 5! is the product 5 · 4 · 3 · 2 · 1, which is equal to 120.

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

factorial = 1;

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

A recursive declaration of the factorial method is arrived at by observing the following relationship:

n! = n · (n – 1)!

For example, 5! is clearly ...

Get Java™ How to Program, Seventh 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.