// This file contains several examples of recursive definitions. import java.io.*; import java.util.*; public class Recurse2 { public static void main(String[] args) { System.out.println(stutter(-348)); System.out.print("Binary representation of -39 = "); writeBinary(-39); System.out.println(); 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)); } } // returns the integer obtained by replacing every digit of n with two of // that digit. For example, stutter(348) returns 334488. public static int stutter(int n) { if (n < 0) { return -stutter(-n); } else 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); } } // 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); } } }