import java.util.Scanner; /** Formula2.java - Example program illustrating how to use recursion * in simple examples involving some recursive formula. * Note that in each recursive function there is a base case, and * a recursive case. We need the base case to know when the recursion stops. * (This time, with diagnostic output to show the recursion.) */ public class Formula2 { public static void main(String [] args) { System.out.print("Enter a positive integer: "); Scanner kbd = new Scanner(System.in); int a = Integer.parseInt(kbd.nextLine()); System.out.printf("You entered %d\n", a); System.out.printf("Odd number # %d is %d\n", a, odd(a)); System.out.printf("%d factorial is %d\n", a, fact(a)); System.out.printf("Term # %d in Fibonacci sequence is %d\n", a, fib(a)); } public static int odd(int n) { System.out.printf("odd(%d): start\n", n); if (n == 1) { System.out.printf("odd(%d): base case, returning 1\n", n); return 1; } else { System.out.printf("odd(%d): Making recursive call odd(%d)\n", n, n-1); int returnValue = 2 + odd(n-1); System.out.printf("odd(%d): After recursive call, returning %d\n", n, returnValue); return returnValue; } } public static int fact(int n) { System.out.printf("fact(%d): start\n", n); if (n == 0) { System.out.printf("fact(%d): base case, returning 1\n", n); return 1; } else { System.out.printf("fact(%d): Making recursive call fact(%d)\n", n, n-1); int returnValue = n * fact(n-1); System.out.printf("fact(%d): After recursive call, returning %d\n", n, returnValue); return returnValue; } } public static int fib(int n) { System.out.printf("fib(%d): start\n", n); if (n <= 2) { System.out.printf("fib(%d): base case, returning 1\n", n); return 1; } else { System.out.printf("fib(%d): Making left recursive call to fib(%d)\n", n, n-1); int leftValue = fib(n-1); System.out.printf("fib(%d): Left recursive call came back with %d\n", n, leftValue); System.out.printf("fib(%d): Making right recursive call to fib(%d)\n", n, n-2); int rightValue = fib(n-2); System.out.printf("fib(%d): Right recursive call came back with %d\n", n, rightValue); int returnValue = leftValue + rightValue; System.out.printf("fib(%d): After recursive calls, returning %d\n", n, returnValue); return returnValue; } } }