Purchase Solution

Visualizing Recursion - Java

Not what you're looking for?

Ask Custom Question

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

Purchase this Solution

Solution Summary

This job specifies how to visualize recursion.

Purchase this Solution


Free BrainMass Quizzes
C# variables and classes

This quiz contains questions about C# classes and variables.

C++ Operators

This quiz tests a student's knowledge about C++ operators.

Javscript Basics

Quiz on basics of javascript programming language.

Basic Computer Terms

We use many basic terms like bit, pixel in our usual conversations about computers. Are we aware of what these mean? This little quiz is an attempt towards discovering that.

Basic Networking Questions

This quiz consists of some basic networking questions.