Key to CSE143X Sample Midterm, Fall 2012 handout #10 1. Expression Value ----------------------------------------------- 4 * (2 + 4) - 3 * 5 9 54 % 10 + 8 * 3 % 9 10 3 * 2 + 4 + "+" + 2 + 3 * 4 "10+212" 2.3 * 3 + 19 / 5 / 2 + 6.0 / 5 9.1 108 / 20 * 3 / 4 / 2.0 + 1.0 / 2 2.0 2. Parameter Mystery. The program produces the following output. students in the beer = 12 beers in the dorm = 125 students in the dorm = 250 beers in the student = 4 3. Method Call Output Produced --------------------------------------- ifElseMystery(4, 15); 15 18 ifElseMystery(7, 17); 27 10 ifElseMystery(12, 5); 15 10 ifElseMystery(16, 8); 28 2 4. Method Call Value Returned -------------------------------------- mystery(6, 0) 0 mystery(8, 1) 8 mystery(3, 3) 17 mystery(4, 2) 10 mystery(1, 4) 24 5. next < 0 next == 0 x > 0 +---------------------+---------------------+---------------------+ Point A | sometimes | sometimes | never | +---------------------+---------------------+---------------------+ Point B | sometimes | never | sometimes | +---------------------+---------------------+---------------------+ Point C | always | never | always | +---------------------+---------------------+---------------------+ Point D | sometimes | sometimes | sometimes | +---------------------+---------------------+---------------------+ Point E | never | always | sometimes | +---------------------+---------------------+---------------------+ 6. Three possible solutions appear below. public static boolean hasMidpoint(int x, int y, int z) { return (2 * x == y + z || 2 * y == x + z || 2 * z == x + y); } public static boolean hasMidpoint(int x, int y, int z) { return (x - y == y - z || x - z == z - y || y - x == x - z); } public static boolean hasMidpoint(int x, int y, int z) { double average = (x + y + z) / 3.0; return (x == average) || (y == average) || (z == average); } 7. One possible solution appears below. public static void flip(Random r, int n) { System.out.print("flips:"); int count = 0; while (count < n) { int result = r.nextInt(2); if (result == 0) { System.out.print(" H"); count++; } else { System.out.print(" T"); count = 0; } } System.out.println(); } 8. One possible solution appears below. public static int numUnique(int[] list) { if (list.length == 0) { return 0; } else { int count = 1; for (int i = 1; i < list.length; i++) { if (list[i] != list[i - 1]) { count++; } } return count; } } 9. One possible solution appears below. public static boolean samePattern(String s1, String s2) { if (s1.length() != s2.length()) return false; for (int i = 0; i < s1.length(); i++) for (int j = i + 1; j < s2.length(); j++) if ((s1.charAt(i) == s1.charAt(j)) != (s2.charAt(i) == s2.charAt(j))) return false; return true; } }
Stuart Reges
Last modified: Fri Oct 19 10:49:12 PDT 2012