Recurse.java
Select all
/* Recurse.java CIS 260 4/6/05 Dave Klick Recursion demonstration */ public class Recurse { public static void main(String[] args) { int i; for (i=0; i<10; i++) System.out.print(fact(i) + " "); System.out.println(); for (i=0; i<10; i++) System.out.print(fib(i) + " "); System.out.println(); countdown(10); toh(4); } static void toh(int n) { toh_move(n, 0, 2); } static void toh_move(int num, int from, int to) { int temp = 3 - from - to; if (num > 1) toh_move(num-1, from, temp); System.out.println("Move disk from pole " + from + " to pole " + to); if (num > 1) toh_move(num-1, temp, to); } static void countdown(int n) { if (n <= 0) System.out.println("Boom!"); else { System.out.print(n + "..."); pause(1); countdown(n-1); } } static void pause(int s) { try { Thread.sleep(s * 1000); } catch (Exception e) {} } static long fib(long n) { if (n < 2) return n; return fib(n-1) + fib(n-2); } static long fact(long n) { if (n < 2) return 1; return n * fact(n-1); } }