Key to CSE143X Midterm, Fall 2013 handout #11 1. Expression Value ----------------------------------------------- 5 * 6 - (4 + 3) * 2 - 2 * 3 10 208 / 20 / 4 + 12 / 10.0 + 0.4 * 2 4.0 8 - 2 + "8 - 2" + (8 - 2) + 8 "68 - 268" 4 * 5 % 6 + 297 % 10 + 4 % 8 13 13 / 2 * 3.0 + 5.5 * 3 / 2 26.25 2. Parameter Mystery. The program produces the following output. he says can we yes Barry says maybe we can we says he we can Sarah says no we can't 3. Method Call Output Produced --------------------------------------- ifElseMystery(14, 14); 14 13 ifElseMystery(4, 5); 7 5 ifElseMystery(10, 5); 12 10 ifElseMystery(2, 8); 3 8 4. Method Call Output Produced --------------------------------------- mystery(0); 1 1 mystery(7); 2 12 mystery(32); 3 123 mystery(256); 4 1234 5. x < y z == 0 z % 2 == 0 +---------------------+---------------------+---------------------+ Point A | sometimes | always | always | +---------------------+---------------------+---------------------+ Point B | always | sometimes | sometimes | +---------------------+---------------------+---------------------+ Point C | sometimes | never | always | +---------------------+---------------------+---------------------+ Point D | sometimes | never | never | +---------------------+---------------------+---------------------+ Point E | never | sometimes | sometimes | +---------------------+---------------------+---------------------+ 6. One possible solution appears below. public static void printMultiples(int n, int times) { System.out.print("The first " + times + " multiples of " + n + " are " + + n); for (int i = 2; i <= times; i++) { System.out.print(", " + i * n); } System.out.println(); } 7. One possible solution appears below. public static int digitRange(int n) { int min = n % 10; int max = n % 10; while (n > 0) { int digit = n % 10; n = n / 10; if (digit < min) { min = digit; } if (digit > max) { max = digit; } } return max - min; } 8. Arrays. One possible solution appears below. public static boolean hasAlternatingParity(int[] list) { for (int i = 0; i < list.length - 1; i++) { if (list[i] % 2 == list[i + 1] % 2) { return false; } } return true; } 9. Programming. Two possible solutions appear below. public static void distributeTokens(int[] tokens, int player) { int n = tokens[player]; tokens[player] = 0; for (int i = 1; i <= n; i++) { tokens[(player + i) % tokens.length]++; } } public static void distributeTokens(int[] tokens, int player) { int num = tokens[player]; tokens[player] = 0; while (num > 0) { player++; if (player == tokens.length) { player = 0; } tokens[player]++; num--; } }
Stuart Reges
Last modified: Tue Oct 22 11:08:59 PDT 2013