Key to CSE143X Sample Midterm, Fall 2016 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. Programming. 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; } 7. File Processing. One possible solution appears below. public static void printDuplicates(Scanner input) { while (input.hasNextLine()) { String line = input.nextLine(); Scanner lineScan = new Scanner(line); String token = lineScan.next(); int count = 1; while (lineScan.hasNext()) { String token2 = lineScan.next(); if (token2.equals(token)) { count++; } if (count > 1 && (!lineScan.hasNext() || !token2.equals(token))) { System.out.print(token + "*" + count + " "); count = 1; } token = token2; } System.out.println(); } } 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 18 17:26:43 PDT 2016