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 (non-recursively) using a for
statement as follows:
A recursive declaration of the factorial ...
Get Java How to Program (early objects), 9/e 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.