// CSE 143, Summer 2016 // This file contains several examples of recursive definitions. import java.io.*; import java.util.*; public class Recurse2 { public static void main(String[] args) { // client to writeBinary writeBinary(384); // is Palindrome client code String[] words = {"madam", "racecar", "seastar", "java"}; for (String s : words) { System.out.println(s + ": " + isPalindrome(s)); } System.out.println(); // pow client code for (int i = 0; i < 5; i++) { System.out.println("2 to the power of " + i + ": " + pow(2, i)); } System.out.println(); // sum client code int[] data = {3, 9, 15, 7}; for (int i = 0; i <= data.length; i++) { int[] test = Arrays.copyOf(data, i); System.out.println("sum of " + Arrays.toString(test) + " = " + sum(test)); } } public static void writeBinary(int n) { if (n < 0) { System.out.print("-"); writeBinary(-n); } else if (n / 2 == 0) { System.out.println(n); } else { writeBinary(n / 2); System.out.print(n % 2); } } // pre : given word is not null, throws a NullPointerException if it is null // returns true if the given word is a palindrome, false otherwise public static boolean isPalindrome(String word) { if (word.length() <= 1) { return true; } else { if (word.charAt(0) == word.charAt(word.length() - 1)) { return isPalindrome(word.substring(1, word.length() - 1)); } else { return false; } } } // alternate solution to isPalindrome public static boolean isPalindrome2(String word) { if (word.length() < 2) { return true; } else { return word.endsWith("" + word.charAt(0)) && isPalindrome(word.substring(1, word.length() - 1)); } } // returns the given base raised to the given exponent public static int pow(int base, int exp) { if (exp == 0) { return 1; } else { return base * pow(base, exp - 1); } } // pre : s != null // post: returns the sum of all elements in s public static int sum(Stack s) { if (s.isEmpty()) { return 0; } else { int n = s.pop(); int rest = sum(s); // remember to push n back! s.push(n); return n + rest; } } public static int sum(int[] list) { if (list == null) { throw new IllegalArgumentException(); } return sum(list, 0); } // returns the sum of the numbers in the given array private static int sum(int[] list, int index) { if (index == list.length) { return 0; } else { return list[index] + sum(list, index + 1); } } }