Key to CSE143X Sample Midterm, Fall 2020 handout #8 1. Expression Value ----------------------------------------------- 3 + 3 * 8 - 2 25 109 % 100 / 2 + 3 * 3 / 2.0 8.5 1 - 3 / 6 * 2.0 + 14 / 5 3.0 1 + "x" + 11 / 10 + " is" + 10 / 2 1x1 is5 10 % 8 * 10 % 8 * 10 % 8 0 2. Parameter Mystery. The program produces the following output. she can't take she with her it can't take her with you you can't take it with you fred can't take her with him 3. Method Call Output Produced --------------------------------------- ifElseMystery(5, 15); 7 15 ifElseMystery(12, 5); 12 1 ifElseMystery(7, 8); 8 9 ifElseMystery(2, 3); 4 -2 ifElseMystery(1, -2); 2 -7 ifElseMystery(1, 1); 2 -4 4. Method Call Output Produced --------------------------------------- mystery(1); 1 mystery(3); 2 mystery(5); 5 mystery(7); 13 5. x > 2 x < n n % x == 0 +---------------------+---------------------+---------------------+ Point A | never | sometimes | sometimes | +---------------------+---------------------+---------------------+ Point B | sometimes | always | sometimes | +---------------------+---------------------+---------------------+ Point C | never | sometimes | sometimes | +---------------------+---------------------+---------------------+ Point D | always | sometimes | sometimes | +---------------------+---------------------+---------------------+ Point E | sometimes | never | sometimes | +---------------------+---------------------+---------------------+ 6. One possible solution appears below. public static boolean checkPrime(int n) { System.out.print("factors of " + n + " = 1"); int count = 1; for (int i = 2; i <= n; i++) { if (n % i == 0) { System.out.print(", " + i); count++; } } System.out.println(); System.out.println("Total factors = " + count); return count == 2; } 7. One possible solution appears below. public static void printDuplicates(Scanner input) { String prevToken = input.next(); int count = 1; while (input.hasNext()) { String nextToken = input.next(); if (nextToken.equals(prevToken)) { count++; } else if (count > 1) { System.out.println(prevToken + "*" + count + " "); count = 1; } prevToken = nextToken; } if (count > 1) { System.out.println(prevToken + "*" + count + " "); } } 8. Arrays. One possible solution appears below. public static boolean isPairwiseSorted(int[] list) { for (int i = 0; i < list.length - 1; i += 2) { if (list[i] > list[i + 1]) { return false; } } return true; } 9. Programming. 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 < s1.length(); j++) { if (s1.charAt(i) == s1.charAt(j) && s2.charAt(i) != s2.charAt(j)) { return false; } if (s2.charAt(i) == s2.charAt(j) && s1.charAt(i) != s1.charAt(j)) { return false; } } } return true; }
Stuart Reges
Last modified: Mon Dec 7 14:44:32 PST 2020