O'Reilly logo

Java™ How to Program, Seventh Edition by P. J. Deitel - Deitel & Associates, Inc., H. M. Deitel - Deitel & Associates, Inc.

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required