// CSE 143, Summer 2016 // This file contains several examples of recursive definitions. import java.io.*; import java.util.*; public class Recurse { public static void main(String[] args) throws FileNotFoundException { writeStars(8); writeStars2(6); Scanner input = new Scanner(new File("input.txt")); reverse(input); System.out.println(stutter(-348)); System.out.println(stutter2(-348)); System.out.println(stutter(1056)); System.out.println(stutter2(1056)); } // iterative method that produces an output line of exactly n stars public static void writeStars(int n) { for (int i = 0; i < n; i++) { System.out.print("*"); } System.out.println(); } // recursive method that produces an output line of exactly n stars public static void writeStars2(int n) { if (n == 0) { System.out.println(); } else { System.out.print("*"); writeStars2(n - 1); } } // post: reads a file, writing the lines to System.out in reverse order public static void reverse(Scanner input) { if (input.hasNextLine()) { // recursive case String line = input.nextLine(); reverse(input); System.out.println(line); } // implicit base case } // 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) { // here's the longer version of stutter if (n < 0) { return -stutter(-n); } else if (n / 10 == 0) { // base case return 10 * n + n; } else { // recursive case int digit = n % 10; int theRest = n / 10; theRest = stutter(theRest); return 100 * theRest + 10 * digit + digit; } } public static int stutter2(int n) { // here's the short ninja version if (n < 0) { return -stutter(-n); } else if (n / 10 == 0) { // base case return 10 * n + n; } else { return 100 * stutter(n / 10) + stutter(n % 10); } } }