Key to CSE142 Midterm, Spring 2022 handout #13
1. Expression Value
-----------------------------------------------
8 * 2 - 2 * 3 10
87 % 10 + 28 % 5 % 2 8
1 + 2 + "3" + 4 + 5 * 6 "33430"
2 * 2.3 + 5 / 2 + 19 / 4 * 2.0 14.6
436 / 10 / 5 - 9 / 2 * 2.5 / 2 3.0
2. Parameter Mystery. The program produces the following output.
bill wants sue to buzz.
hope wants foo to bill.
bill wants sue to hope.
hope wants bill to sue.
3. Method Call Output Produced
---------------------------------------
ifElseMystery(5, 20); 7 0
ifElseMystery(42, 42); 43 41
ifElseMystery(6, 1); 9 0
ifElseMystery(2, 0); 3 -1
ifElseMystery(7, 10); 9 0
ifElseMystery(4, 4); 5 3
4. Method Call Output Produced
---------------------------------------
mystery(1); 1 1
mystery(5); 3 4
mystery(10); 4 8
mystery(42); 6 32
5. 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 |
+---------------------+---------------------+---------------------+
6. One possible solution appears below.
public static void testLuck(Scanner console, int number) {
Random r = new Random();
int numRight = 0;
System.out.println("guess " + number + " one-digit odd numbers");
for (int i = 1; i <= number; i++) {
int answer = r.nextInt(5) * 2 + 1;
System.out.print("guess #" + i + "? ");
int guess = console.nextInt();
if (guess == answer) {
System.out.println("correct!");
numRight++;
} else {
System.out.println("incorrect...answer was " + answer);
}
}
double expected = number / 5.0;
System.out.println("expected correct = " + expected);
System.out.println("you got " + numRight + " correct");
}
7. One possible solution appears below.
public static int printSequenceTo(double value) {
double sum = 0.5;
System.out.print("1/2");
int n = 1;
while (sum < value) {
n++;
System.out.print(" + " + n + "/" + (n + 1));
sum = sum + (double) n / (n + 1);
}
System.out.println(" = " + sum);
return n;
}
8. One possible solution appears below.
public static boolean isConsecutive(int n) {
int lastDigit = n % 10;
n = n / 10;
while (n != 0) {
int nextDigit = n % 10;
n = n / 10;
if (nextDigit != lastDigit - 1) {
return false;
}
lastDigit = nextDigit;
}
return true;
}