/* Author : Michael Robinson Program : recursion.java Purpose : To implement recursion functions In this example we want to find the factorial of 7 The mathematical representation is 7! = 5040 which means 7 * 6 * 5 * 4 * 3 * 2 * 1 We can find the factorial of any number by passing its value to the method factorial( int n ) 7! = 7*6! = 7*720 = 5040 6! = 6*5! = 6*120 = 720 5! = 5*4! = 5*24 = 120 4! = 4*3! = 4*6 = 24 3! = 3*2! = 3*2 = 6 2! = 2*1! = 2*1 = 2 1! = 1 = 1 = 1 //base case note 0! = 1 always Updated : January 13, 2099 */ class recursion { public static long factorial( int n ) { System.out.printf( "Processing factorial( %d )\n\n", n ); if( n <= 1 ) //base case { System.out.printf( "Reached base case, returning %d\n\n", n); System.out.printf( "Now returning the accumulated " + "values from RAM\n" ); return 1; } else { System.out.printf( "Doing recursion by calling" + "factorial( %d-1 )\n", n ); //doing recursion by calling factorial(n - 1) long counter = n * factorial(n - 1); System.out.printf( "Receiving results of " + "factorial( %d ) = %d * %d! =" + " %d\n", n, n, (n-1), counter ); return counter; } }//end public static long fact(long n) public static void main(String args[]) { System.out.println( "\nRecursion Program" ); System.out.println( "=================" ); System.out.println( "\nThe factorial of 7 = " + factorial( 7 ) ); }//end public static void main(String args[]) }//end class recursion