/** * Demos of recursion. * @author Sean Barker */ public class Recursion { // iterative (not recursive) factorial implementation public static int fact_iter(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } // recursive factorial implementation public static int fact(int n) { if (n == 0) { // base case return 1; } else { // recursive case return fact(n - 1) * n; } } // raise base to a power public static double exp(double base, int power) { if (power == 0) { return 1; } else { return base * exp(base, power - 1); } } // find the nth fibonacci number public static int fib(int n) { if (n == 0 || n == 1) { return 1; } else { return fib(n - 1) + fib(n - 2); } } // find the length of a string public static int strlen(String s) { if (s.equals("")) { return 0; } else { return 1 + strlen(s.substring(1)); } } // return the reverse of a string public static String reverse(String s) { if (s.equals("")) { return ""; } else { return reverse(s.substring(1)) + s.charAt(0); } } // return a string that is the given string with all // occurrences of the character c removed public static String removeChar(String s, char c) { if (s.equals("")) { return s; } char firstChar = s.charAt(0); if (firstChar == c) { return removeChar(s.substring(1), c); } else { return firstChar + removeChar(s.substring(1), c); } } }