Key to CSE143X Midterm, Fall 2012 handout #12 1. Expression Value ----------------------------------------------- 3 * (5 - 2) - 3 - 2 * 2 2 4 * 7 % 8 + 132 % 10 + 3 % 4 9 27 / 5 / 2 + 3.4 * 2 - 1.1 * 2 6.6 9 + 9 + "9 + 9" + 9 + 9 "189 + 999" 19 / 2 / 2.0 + 2.5 * 6 / 2 + 0.5 * 4 14.0 2. Parameter Mystery. The program produces the following output. to walk the walk is good to hear the good is bad to feel the walk is song to feel the talk is bad 3. Method Call Output Produced --------------------------------------- ifElseMystery(1, 8); 3 8 ifElseMystery(3, 5); 5 0 ifElseMystery(4, 5); 5 6 ifElseMystery(8, 6); 8 2 4. Method Call Output Produced --------------------------------------- mystery(2); 1 2 mystery(4); 2 2 mystery(24); 4 3 mystery(28); 3 7 5. x > y z == 0 x == y +---------------------+---------------------+---------------------+ Point A | sometimes | always | sometimes | +---------------------+---------------------+---------------------+ Point B | sometimes | sometimes | never | +---------------------+---------------------+---------------------+ Point C | always | never | never | +---------------------+---------------------+---------------------+ Point D | never | never | never | +---------------------+---------------------+---------------------+ Point E | never | sometimes | always | +---------------------+---------------------+---------------------+ 6. One possible solution appears below. public static int quadrant(double x, double y) { if (x > 0 && y > 0) { return 1; } else if (x < 0 && y > 0) { return 2; } else if (x < 0 && y < 0) { return 3; } else if (x > 0 && y < 0) { return 4; } else { // at least one equals 0 return 0; } } 7. One possible solution appears below. public static int minHailstoneValue(int n, int steps) { int min = n; for (int i = 1; i < steps; i++) { if (n % 2 == 0) { n = n / 2; } else { n = 3 * n + 1; } if (n < min) { min = n; } } return min; } 8. One possible solution appears below. public static boolean isSorted(double[] list) { for (int i = 0; i < list.length - 1; i++) { if (list[i] > list[i + 1]) { return false; } } return true; } 9. One possible solution appears below. public static void printCompact(String s) { boolean inWord = false; boolean firstWord = true; for (int i = 0; i < s.length(); i++) { char next = s.charAt(i); if (next == ' ') { inWord = false; } else { // next != ' ' if (!inWord) { inWord = true; if (firstWord) { firstWord = false; } else { System.out.print(' '); } } System.out.print(next); } } System.out.println(); }
Stuart Reges
Last modified: Tue Oct 23 17:36:43 PDT 2012