Key to CSE142 Sample Midterm, Spring 2005 handout #16
1. Expression Value
-----------------------------------------------
13 + 2 * 5/3 16
2.5 * 4 * 3/12 + 1.5 4.0
85 % 10 + 4 % 10 - 17 % 3 7
2 + 3 + "." + (3 + 4) + 2 * 3 "5.76"
482/10/5/2.0 * 2 + 14/5 11.0
2. Parameter Mystery. The program produces the following output.
a two and a queen beats a king
a queen and a queen beats a b
a two and a king beats a five
a king and a two beats a queen
a queen and a two beats a five
3. Method Call Value Returned
--------------------------------------
mystery(6, 0) 0
mystery(8, 1) 8
mystery(3, 3) 17
mystery(4, 2) 10
mystery(1, 4) 24
4. next == 0 prev == 0 next == prev
+---------------------+---------------------+---------------------+
Point A | sometimes | always | sometimes |
+---------------------+---------------------+---------------------+
Point B | never | sometimes | sometimes |
+---------------------+---------------------+---------------------+
Point C | never | never | always |
+---------------------+---------------------+---------------------+
Point D | sometimes | never | sometimes |
+---------------------+---------------------+---------------------+
Point E | always | sometimes | sometimes |
+---------------------+---------------------+---------------------+
5. Three possible solutions appear below.
public static int numUnique(int x, int y, int z) {
if (x == y && y == z)
return 1;
else if (x != y && x != z && y != z)
return 3;
else
return 2;
}
public static int numUnique(int x, int y, int z) {
if (x == y)
if (y == z)
return 1;
else
return 2;
else // x != y
if (y == z)
return 2;
else if (x == z)
return 2;
else
return 3;
}
public static int numUnique(int x, int y, int z) {
if (x == y && y == z)
return 1;
else if (x == y || x == z || y == z)
return 2;
else
return 3;
}
6 One possible solution appears below.
public static void printRange(int low, int high) {
if (low > high)
System.out.println("[]");
else {
System.out.print("[" + low);
for (int i = low + 1; i <= high; i++)
System.out.print("," + i);
System.out.println("]");
}
}
7. Three possible solutions appear below.
public static int numWords(String s) {
int count = 0;
boolean inWord = false;
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) == ' ')
inWord = false;
else if (!inWord) {
count++;
inWord = true;
}
return count;
}
public static int numWords(String s) {
int count = 0;
for (int i = 1; i < s.length(); i++)
if (s.charAt(i - 1) == ' ' && s.charAt(i) != ' ')
count++;
if (s.length() > 0 && s.charAt(0) != ' ')
count++;
return count;
}
public static int numWords(String s) {
int count = 0;
int i = 0;
while (i < s.length()) {
while (i < s.length() && s.charAt(i) == ' ')
i++;
if (i < s.length()) {
count++;
while (i < s.length() && s.charAt(i) != ' ')
i++;
}
}
return count;
}