/** Recursion.java -- Let's write some recursive functions. Practically * anything you can do with a loop, you can also do recursively. */ import java.util.Scanner; import java.util.StringTokenizer; public class Recursion { private static int [] a = { 7, 2, 9, 4, 1, 6 }; public static void main(String [] args) { // simple I/O examples System.out.println("List of numbers: " + count(10)); System.out.println("The sum 1..10 equals " + sum(10)); System.out.println("Star pattern:\n" + triangle(5)); // practice with strings Scanner kbd = new Scanner(System.in); System.out.print("\nEnter a string: "); String s = kbd.nextLine(); System.out.println("Reversal is: " + reverse(s)); System.out.println("palindrome() returns " + palindrome(s)); // practice with a string tokenizer System.out.print("\nEnter a list of numbers: "); s = kbd.nextLine(); StringTokenizer tok = new StringTokenizer(s, ", "); System.out.println("sum is " + sumToken(tok)); // practice with arrays System.out.println("\nLargest element of array is " + max(a, 0)); System.out.println("Array sum is " + sumArray(a, 0)); // to/from binary System.out.print("\nEnter a positive integer: "); int n = Integer.parseInt(kbd.nextLine()); s = toBinary(n); System.out.println("Binary equivalent is " + s); n = toInt(s); System.out.println("Converting back to integer: " + n); } public static String count(int n) { } public static int sum(int n) { } // Print a row (horizontal line) of stars. public static String starLine(int n) { } // Make a right triangle filled with stars. Makes use of starLine() // above to simulate a nested loop. // In the recursive case, we make sure to print the first n-1 rows, then // append the current row of stars, and then a newline. public static String triangle(int n) { } public static String reverse(String s) { } public static boolean palindrome(String s) { } // Recursion can also replace a "while" loop. // Here we find the sum of numbers that are tokens in a string. public static int sumToken(StringTokenizer tok) { } // Find the largest element of (at least part of) an array. // We take 2 parameters - the array and the starting index. public static int max(int [] a, int start) { } // Find the sum of the elements in an array. Analogous to finding the max. public static int sumArray(int [] a, int start) { } // Convert a positive integer value to a binary string. public static String toBinary(int n) { } // Convert an unsigned binary string to an integer. public static int toInt(String s) { } }