Skip to content

Commit 4ca1015

Browse files
committed
Create a Factorial Calculator
1 parent 9e7e182 commit 4ca1015

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* Fig. 18.3: FactorialCalculator
3+
* Recursive factorial method.
4+
*/
5+
public class FactorialCalculator
6+
{
7+
// recursive method factorial (assumes its parameter is >= 0)
8+
public long factorial (long number)
9+
{
10+
if (number <= 1)
11+
return 1; // test for base case
12+
else
13+
return number * factorial(number - 1);
14+
} // end method factorial
15+
16+
// output factorials for values 0-21
17+
public static void main(String[] args)
18+
{
19+
// calculate the factorials of 0 through 21
20+
for (int counter = 0; counter <= 21; counter++)
21+
System.out.printf("%d! = %d\n", counter, factorial(counter) );
22+
}
23+
}

0 commit comments

Comments
 (0)