/** * Demos of simple problems solved using recursion. * @author Sean Barker */ public class RecursionDemo { // iterative (not recursive!) implementation of factorial public static int factIter(int n) { int result = 1; for (int i = 1; i <= n; i++) { result = result * i; } return result; } // recursive implementation of factorial public static int fact2(int n) { if (n == 0) { // base case return 1; } else { // recursive case return n * fact2(n - 1); } } // sums values from 0 to n public static int sum(int n) { if (n == 0) { return 0; } else { return n + sum(n - 1); } } // compute base raised to power public static int exp(int base, int power) { if (power == 0) { return 1; } else { return base * exp(base, power - 1); } } // compute the nth fibonacci number (starting from 0) public static int fib(int n) { if (n <= 1) { return 1; } else { return fib(n - 1) + fib(n - 2); } } // return the length of s (without calling length) public static int strlen(String s) { if (s.equals("")) { return 0; } else { return strlen(s.substring(1)) + 1; } } // return a reversed version of s // allowed string methods: equals, substring, charAt public static String reverse(String s) { if (s.equals("")) { return ""; } else { String subproblem = reverse(s.substring(1)); return subproblem + s.charAt(0); } } // return s with all instances of c removed public static String removeChar(String s, char c) { if (s.equals("")) { return ""; } else { String subcall = removeChar(s.substring(1), c); if (s.charAt(0) == c) { return subcall; } else { return s.charAt(0) + subcall; } } } }