// Allison Obourn // CSE 143 - lecture 10 // Recursion practice and examples import java.io.*; public class Recursion { public static void main(String[] args) { System.out.println(pow(3, 4)); System.out.println(pow(2, 0)); System.out.println(); printBinary(7); // 111 System.out.println(); printBinary(12); // 1100 System.out.println(); printBinary(42); // 101010 System.out.println(); crawl(new File("../..")); } // Returns the result of raising the base to the specified exponent. // pre: exp >= 0, throws IllegalArgumentException otherwise public static int pow(int base, int exp) { if (exp < 0) { throw new IllegalArgumentException(); } else if(exp == 0) { return 1; } else if (exp % 2 == 0) { return pow(base * base, exp / 2); } else { // 2^1 = 2 = 2 // 2^2 = 4 = 2 * 2 // 2^3 = 8 = 2 * 2 * 2 // 2^4 = 16 = 2 * 2 * 2 * 2 = 2 * 2^3 return base * pow(base, exp - 1); } } // Prints the given decimal value in binary // pre: decimal >= 0 public static void printBinary(int decimal) { if(decimal < 2) { System.out.print(decimal); } else { int last = decimal % 2; int rest = decimal / 2; printBinary(rest); printBinary(last); } } // Prints information about this file, // and (if it is a directory) any files inside it. public static void crawl(File f) { crawl(f, ""); } // Prints the name of the given file at the specified level of indentation. // If the file is a directory, prints its content. // pre: the file exists private static void crawl(File f, String indent) { System.out.println(indent + f.getName()); if(f.isDirectory()) { File[] files = f.listFiles(); for(int i = 0; i < files.length; i++) { crawl(files[i], " " + indent); } } } }