computer science homework

profileJoshuaTT
ica03_start.txt

final static Scanner cin = new Scanner(System.in); public static void main(String[] args) { out.print("Enter n: "); int n = cin.nextInt(); long result = fact(n, 0); out.println("\n" + n + "! = " + result); /* code for calling fib is commented out long f = fib(n); out.println("\nfib(" + n + ") = " + f); */ } // end main // this is the standard recursive factorial computation static long fact(int n) { if (n < 0) terminate("Negative argument value not allowed, program ended"); if (n == 0) return 1; else return n * fact(n - 1); } // end fact // this is the self-tracing recursive factorial computation static long fact(int n, int level) { if (n < 0) terminate("Negative argument value not allowed, program ended"); long result; indent(level); out.println("Entering fact, n = " + n); if (n == 0) result = 1; else result = n * fact(n - 1, level + 1); indent(level); out.println("Exiting fact, n = " + n + ", return value = " + result); return result; } // end fact // standard fibonacci number computation using recursion static long fib(int n) { if (n < 0) terminate("Negative argument value not allowed, program ended"); if (n <= 1) return n; else return fib(n - 1) + fib (n - 2); } // end fib private static void indent(int level) { for(int Lcv = 1; Lcv <= 3 * level; Lcv++) out.print(' '); } // end indent private static void terminate(String errorMessage) { out.println(errorMessage); System.exit(1); } // end terminate