/* * Intro to Programming CSE 1310 * University of Texas at Arlington */ package coderecursion26.ct17; import java.util.Scanner; /** * * @author jcmtiernan */ public class CodeRecursion26Ct17 { /** * @param args the command line arguments */ public static void main(String[] args) { // calling a recursive method int testValue = 0; double testFac = 0; Scanner input = new Scanner(System.in); System.out.print("Please enter a positive integer value to take the factorial of: "); testValue = input.nextInt(); testFac = fac(testValue); System.out.println(""); System.out.println("The result of fac for "+testValue+" is "+testFac); } /** * Method fac - factorial function written recursively. * The function factorial can be generalized as shown below. * Method fac takes the generalization and implements it. 0! = 1 // base case – stops the recursion 1! = 0! * 1 // examples 2! = 1! * 2 3! = 2! * 3 k! = (k – 1)! * k // general (recursive) case – calls itself with different parameters To write a recursive function you must have: At least one base case, may have more than one base case At least one recursive case May also have an error case (or condition) Function header ( with access “static” return_type name (parameters) { test for the base case return action for base case possible other tests with other actions recursive call using return statement } public static int fac( int k ) { if ( k == 0 ) return 1; return fac(k – 1) * k ; } * @param k * @return */ public static int fac(int k) { if (k < 0) return 0; if (k == 0) return 1; System.out.println("in fac, k is "+k); return (fac(k-1) * k); } }