// 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.println("Stuttering 348 = " + stutter(348)); System.out.print("Binary representation of 45703 = "); writeBinary(45703); System.out.println(); 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)); } } // Returns the given integer with each digit repeated twice // pre: n > 0 public static int stutter(int n) { if (n < 10) { return n * 11; } else { return 100 * stutter(n / 10) + stutter(n % 10); } } // 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 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); } } }