Key to CSE142 Midterm, Winter 2012 handout #15
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. Four 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) {
if (x == (y + z) / 2.0) {
return true;
}
if (y == (x + z) / 2.0) {
return true;
}
if (z == (x + y) / 2.0) {
return true;
}
return false;
}
public static boolean hasMidpoint(int x, int y, int z) {
double average = (x + y + z) / 3.0;
if (x == average) {
return true;
}
if (y == average) {
return true;
}
if (z == average) {
return true;
}
return false;
}
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 boolean increasingDigits(int n) {
int prev = n % 10;
n = n / 10;
while (n > 0) {
int digit = n % 10;
if (digit >= prev) {
return false;
}
n = n / 10;
prev = digit;
}
return true;
}
Stuart Reges
Last modified: Fri Sep 16 16:16:07 PDT 2011