PRACTICE EXAM 2 SAMPLE ANSWERS 1a) 1+4+7+10+13 = 35 b) total 5*2 = 10 10*2 = 20 20*2 = 40 40*2 = 80 80*2 = 160 <-- 100 never reached. infinite loop. Nothing prints out c) result 1+1 = 2 2+2 = 4 4+4 = 8 8+8 = 16 16+16 = 32 32+32 = 64 64+64 = 128 > 100. Exit loop. result = 128 d) i is not greater than 1. Loop never gets executed. print out initial value of product = 1. 2a) i j sum product 1 1 1 1 1 2 1 1 1 2 2 3 1 3 3 1 1 3 3 2 3 3 3 3 6 3 18 product = 18 b) i j sum product 1 1 1 1 1 2 1 2 1 2 2 4 1 4 3 1 5 4 3 2 7 4 3 3 10 4 40 product = 40 It does not yield the same answer since sum is not reset back to 0 each time the outer loop repeats. So sum continues to get larger and larger, making the product larger than before. c) int product = 1; int i=1; while (i<4) { int sum = 0; int j = 1; while (j<=i) { sum += j; j++; } product *= sum; i++; } System.out.println(product); 3a) score = new int[30]; b) for (int i=0; i max) max = score[i]; } 4. public static int countTemps(double[] tempArray, double threshold) { int count = 0; for (int i = 0; i < tempArray.length; i++) { if (threshold < tempArray[i]) count = count+1; } return count; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); double[] tempValues = { 23.1, 15.3, 64.4, 23.6, 86.4, 49.3, 77.3 }; System.out.println("Input the temperature threshold cutoff: "); double cutoff = scan.nextDouble(); System.out.println("The number of temperatures above the threshold is " + countTemps(tempValues, cutoff)); } 5. public class MyDiceGame { public static void main(String[] args) { Die die1 = new Die(); Die die2 = new Die(); int round = 0; int score = 0; while (round<10 && score<70) { round++; int value1 = die1.roll(); int value2 = die2.roll(); System.out.println(); System.out.println("Round "+round); if (value1!=value2) score = score+value1+value2; else { if (score<10) score = 0; else score -= 10; } System.out.println("Your new score is: " + score); } if (score>=70) System.out.println("WINNER"); else System.out.println("LOSER"); } }