// 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.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)); } } // 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); } } }