/* * Intro to Programming CSE 1310 * University of Texas at Arlington */ package coderecursion2nov17; import java.util.Scanner; /** * * @author jcmtiernan */ public class CodeRecursion2Nov17 { /** * @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 as an index to find Fibonacci value of: "); testValue = input.nextInt(); testFac = fib(testValue); System.out.println(""); System.out.println("The result of fib 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); } /** * Fibonacci series * Values: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 * Index: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 * * m is the index * fib(m) = fib(m-1) + fib(m-2) */ public static int fib(int m) { System.out.println("in fib with m = "+m); if ((m == 0) || (m == 1)) // base cases return m; if (m < 0) // error case return -1; return fib(m-1)+fib(m-2); } }