// Zorah Fung, CSE 143 // This program prints out various number of stars using // both iterative and recursive solutions to the problem public class Stars { public static void main(String[] args) { writeStars(3); writeStars(15); writeStars(0); // edge case } // Prints a line containing the given number of stars. // Precondition: n >= 0 public static void writeStars(int n) { if (n == 0) { // base case (simplest instance of the problem) System.out.println(); } else { // recursive case System.out.print("*"); // smallest piece of the problem writeStars(n - 1); // solve a smaller problem } /* * It can be useful to write out specific cases to see the pattern for * the recursive case * * else if (n == 2) { * System.out.print("*"); * writeStars(1); * } else if (n == 3) { * System.out.print("*"); * writeStars(2); * } */ } // Prints a line containing the given number of stars. // Precondition: n >= 0 public static void writeStars2(int n) { // The iterative solution we're used to for (int i = 0; i < n; i++) { System.out.print("*"); } System.out.println(); } // Prints a line containing the given number of stars. // Precondition: n >= 0 public static void writeStars3(int n) { // An alternate iterative solution where the similarities // to recursion can be seen more easily while (n > 0) { // "recursive" case System.out.print("*"); // smallest piece of the problem n--; // make the problem smaller } // assertion: n == 0 System.out.println(); // base case } }