You may want to add such display capabilities to other


It is interesting to watch recursion "in action." Modify the factorial method in Fig. 15.3 to print its local variable and recursive-call parameter. For each recursive call, display the outputs on a separate line, and add a level of indentation. Do your utmost to make the outputs clear, interesting and meaningful. Your goal here is to design and implement an output format that makes it easier to understand recursion. You may want to add such display capabilities to other recursion examples and exercises throughout the text.

// FactorialCalculator.java
// Recursive factorial method.

public class FactorialCalculator
{
// recursive declaration of method factorial
public long factorial( long number )
{
if ( number <= 1 ) // test for base case
return 1; // base cases: 0! = 1 and 1! = 1
else // recursion step
return number * factorial( number - 1 );
} // end method factorial

// output factorials for values 0-10
public void displayFactorials()
{
// calculate the factorials of 0 through 10
for ( int counter = 0; counter <= 10; counter++ )
System.out.printf( "%d! = %dn", counter, factorial( counter ) );
} // end method displayFactorials
} // end class FactorialCalculator
---------------------------------------------------------------------------

// Fig. 15.4: FactorialTest.java
// Testing the recursive factorial method.

public class FactorialTest
{
// calculate factorials of 0-10
public static void main( String args[] )
{
FactorialCalculator factorialCalculator = new FactorialCalculator();
factorialCalculator.displayFactorials();
} // end main
} // end class FactorialTest
----------------------------------------------------------------------

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800

Attachment:- FactorialCalculator.zip

Solution Preview :

Prepared by a verified Expert
JAVA Programming: You may want to add such display capabilities to other
Reference No:- TGS01250846

Now Priced at $20 (50% Discount)

Recommended (94%)

Rated (4.6/5)