// Zorah Fung, CSE 143 // This file contains several examples of recursive definitions. import java.util.*; public class Recursion { public static void main(String[] args) { System.out.print("Binary representation of 45703 = "); writeBinary(45703); System.out.println(); System.out.println(isPalindrome("racecar")); System.out.println(isPalindrome("banana")); int[] data = {3, 9, 15, 7}; for (int i = 0; i <= data.length; i++) { int[] test = Arrays.copyOfRange(data, data.length - i, data.length); System.out.println("sum of " + Arrays.toString(test) + " = " + sum(test)); } } // writes the binary representation of n to System.out public static void writeBinary(int n) { if (n < 0) { System.out.print("-"); writeBinary(-n); } else if (n < 2) { System.out.print(n); } else { writeBinary(n / 2); System.out.print(n % 2); // we could also call writeBinary(n % 2) } } // returns true if the given string is the same forwards as // backwards, false otherwise. public static boolean isPalindrome(String s) { if (s.length() <= 1) { return true; } else { char first = s.charAt(0); char last = s.charAt(s.length() - 1); String middle = s.substring(1, s.length() - 1); return first == last && isPalindrome(middle); } } // returns the sum of the numbers in the given array public static int sum(int[] list) { return sum(list, 0); } // computes the sum of the list starting at the given index private static int sum(int[] list, int index) { if (index == list.length) { return 0; } else { return list[index] + sum(list, index + 1); } } }