/** Formula.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. */ import java.io.*; public class Formula { public static void main(String [] args) throws IOException { System.out.print("Enter a positive integer: "); BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in)); int a = Integer.parseInt(kbd.readLine()); 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) { if (n == 1) return 1; else return 2 + odd(n-1); } public static int fact(int n) { if (n == 0) return 1; else return n * fact(n-1); } public static int fib(int n) { if (n <= 2) return 1; else return fib(n-1) + fib(n-2); } }