A good answer might be:

int fact( int N )
{
  if ( N == 0 )
  
    return 1;
    
  else
  
    return N * fact( N-1 );
}

Dynamic Thinking

If you have a correct math-like definition of what you want to do, then transforming it into a Java method should be nearly mechanical.

But, you can think about how the code runs. The diagram shows the how the activation chain grows as the method executes.

Each activation except the base case requires another activation. This is because the statement return N * fact( N-1 ) needs a value for fact( N-1 ) before the multiplication can be done. (Click on the diagram to see the activation chain grow.)

int fact( int N )
{
  if ( N == 0 )
    return 1;
  else
    return N * fact( N-1 ) ;
}

When the base case is reached, return values start being passed up the chain. After an activation has returned a value to its caller it is no longer active. The diagram shows this as a dotted circle.



QUESTION 4:

(Practice Dynamic Thinking: ) What would happen if fact() were called with a parameter of -1?