// Helene Martin, CSE 142 // These examples demonstrate ways to address fencepost problems, applications of // the cumulative sum pattern and methods that return. public class LoopsDemo { public static void main(String[] args) { //printConsonants("all work and no play make jack a dull boy"); //printLetters("all work and no play make jack a dull boy"); System.out.println(countFactors(20)); printPrimes(50); } // prints all primes up to and including the max // precondition: max is >= 2 public static void printPrimes(int max) { System.out.print(2); // extra 'post' in fencepost problem for (int i = 3; i <= max; i++) { if (countFactors(i) == 2) { System.out.print(", " + i); } } } // counts and returns the factors of a particular number public static int countFactors(int num) { int count = 0; for (int i = 1; i <= num; i++) { if (num % i == 0) { count++; } } return count; } // prints non-vowel letters from the phrase // e.g.: vowels -> vwls public static void printConsonants(String phrase) { for (int i = 0; i <= phrase.length() - 1; i++) { char c = phrase.charAt(i); if (c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u') { System.out.print(c); } } } // prints letters from the phrase separated by commas // e.g.: vowels -> v, o, w, e, l, s // this solution takes out the extra 'post' last public static void printLetters(String phrase) { for (int i = 0; i < phrase.length() - 1; i++) { char c = phrase.charAt(i); System.out.print(c + ", "); } System.out.print(phrase.charAt(phrase.length() - 1)); // post } // prints letters from the phrase separated by commas // e.g.: vowels -> v, o, w, e, l, s // this solution takes out the extra 'post' first public static void printLetters2(String phrase) { System.out.print(phrase.charAt(0)); // post for (int i = 1; i < phrase.length(); i++) { char c = phrase.charAt(i); System.out.print(", " + c); // switch order in loop } } }