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 · (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 calculation for integers greater than 1 is arrived at by observing the following ...

Get Java™ How To Program (Early Objects), Tenth 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.