Example: direct recursive method
public class myClass { .... public (static) ... recursiveMethod(...) { ... ... recursiveMethod(new set of parameters) ... ... } } |
Example: indirect recursive method
public class myClass { .... public (static) ... recursiveMethod1(...) { ... ... recursiveMethod2(.....) ... ... } public (static) ... recursiveMethod2(...) { ... ... recursiveMethod1(.....) ... ... } } |
General structure of a Recursive Solution
public ... recursiveSolve("problem N") { if ( "problem N" is a base case ) { return( (known) solution for base case ); } else { Split "problem N" into k smaller "problems < N" and a "problem X" sol_1 = recursiveSolve("smaller problem 1"); sol_2 = recursiveSolve("smaller problem 2"); .... sol_k = recursiveSolve("smaller problem k"); solution = solve "problem X" using the solutions "sol_1", "sol_2", ..., "sol_k" return(solution); } }
|
The recursive program:
Recursive Method to find Factorial of integer N
public class Numeric { public static int factorial(int N) { if ( N == 0 ) { return( 1 ); // (known) solution for base case } else { int sol; int solX; sol = factorial(N-1); solX = N * sol; return(solX); } } } |