Key to CSE142 Midterm, Fall 2004 handout #20 Note: Different versions of the test had slightly different orders for the subparts of questions 1-4. Each test had the same subparts, but they appeared in slightly different orders. 1. Expression Value ----------------------------------------------- 208 % 10 - 90 % 55 % 10 3 31 % 8/3 * 1.2 2.4 203/10/2.0/4 2.5 79 % (14/3) - 6 * 7/3 -11 2 + 3 + "-" + 8 * 2 + 3 * 4 5-1612 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 students in the classroom = 24 3. Method Call Value Returned -------------------------------------- mystery(976, 9235) 9 mystery(348, 34298) 34 mystery(2974, 2184) 2 mystery(82, 19) 0 mystery(2348, 239) 23 4. x > y z > 0 y % 2 == 0 +---------------------+---------------------+---------------------+ Point A | sometimes | never | never | +---------------------+---------------------+---------------------+ Point B | always | sometimes | sometimes | +---------------------+---------------------+---------------------+ Point C | sometimes | always | sometimes | +---------------------+---------------------+---------------------+ Point D | sometimes | always | always | +---------------------+---------------------+---------------------+ Point E | never | sometimes | sometimes | +---------------------+---------------------+---------------------+ 5. Three possible solutions appear below. public static void betOnce(Scanner console, int number) { System.out.print("Do you want to bet on 1) low or 2) high? "); int bet = console.nextInt(); System.out.println("The number was " + number); if (bet == 1) if (number == 0) System.out.println("You lose"); else if (number <= 18) System.out.println("You win"); else System.out.println("You lose"); else if (number > 18) System.out.println("You win"); else System.out.println("You lose"); } public static void betOnce(Scanner console, int number) { System.out.print("Do you want to bet on 1) low or 2) high? "); int bet = console.nextInt(); System.out.println("The number was " + number); if (number == 0) System.out.println("You lose"); else if ((bet == 1 && number <= 18) || (bet == 2 && number > 18)) System.out.println("You win"); else System.out.println("You lose"); } public static void betOnce(Scanner console, int number) { System.out.print("Do you want to bet on 1) low or 2) high? "); int bet = console.nextInt(); System.out.println("The number was " + number); int result = (number - 1)/18 + 1; if (number != 0 && result == bet) System.out.println("You win"); else System.out.println("You lose"); } 6 One possible solution appears below. public static double sumTo(int n) { double sum = 0.0; for (int i = 1; i <= n; i++) sum = sum + 1.0/i; return sum; } 7. One possible solution appears below. public static int digitSum(int n) { int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; }
Stuart Reges
Last modified: Wed Nov 10 13:05:45 PST 2004