/* 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 NOTE: JAVA WILL START GIVING WRONG VALUES FOR FACTORIAL RESULTS CREATE A VALIDATION SECTION TO DETECT AND STOP AT THAT POINT Updated : January 13, 2012 */ import java.util.Scanner; class recursion { public static void pause() { System.out.print( "Press any key to continue ..."); Scanner anykey = new Scanner(System.in); String temp = anykey.nextLine(); } public static long factorial( int n ) { System.out.printf("Processing factorial( %d )\n", n); pause(); if(n <= 1) //base case { System.out.printf("\nReached base case, returning %d\n\n", n); System.out.printf("Now returning the accumulated values from RAM\n"); return 1; } else { System.out.printf("\nDoing recursion by calling factorial( %d - 1 )\n", n ); long counter = n * factorial(n - 1); //doing recursion by calling 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.print( "Enter an integer to do recursion : "); Scanner recur = new Scanner(System.in); int recursion = recur.nextInt(); factorial( recursion ); } }//end class recursion