public int factorial( int N ) { if ( N == 0 ) return 1; else return N * factorial( N-1 ); }
If you have a correct math-like definition of what you want to do, then transforming it into a Java method is almost mechanical.
But, you can also think about what happens as the method runs. This is a dynamic view of recursion. The diagram shows the how the activation chain grows as the method executes.
Each activation except the base case requires another activation to be added to the chain. This is because the statement
return N * factorial( N-1 )
needs a value for factorial( N-1 )
before the
multiplication can be done.
public int factorial( int N ) { if ( N == 0 ) return 1; else return N * factorial( N-1 ) ; }
When the base case is reached, return values can be passed up the chain. (Sometimes this is called "unwinding the recursion".)
After an activation has returned a value to its caller it is no longer active. The diagram shows this as a dotted circle.
(Click on the diagram to see the activation chain grow.)
(Practice Dynamic Thinking: ) What would happen if
factorial()
were called with
a parameter of -1?