computer science 114 midterm1 practice problem solutions

22
CSE114 Midterm 1 - Practice Problem Solutions 1) What is the output of the following statement? System.out.println((2.0 + 3) + 3); a) 5.03 b) 8.0 c) 8 d) 53 e) 2.033 Even though you are probably used to string concatenation inside of print statements (such as “abc” + x which yields “abcx”), you can still do math inside them. Since there are no strings anywhere in the expression (just numbers), Java adds them up normally. If we were to change the expression to ((2.0 + 3 + “”) + 3), the output would be “5.03”. Java evaluates expressions from left to right, so it would add 2.0 and 3 to produce 5.0 (double + int = double), and once we add the empty string (“”) to it, Java will now interpret it as a string and thus we can no longer do arithmetic with it. Similarly, if the epxression was ((2.0 + “” + 3) + 3), then the output would be “2.033”.

Upload: melancholy

Post on 11-Jan-2016

25 views

Category:

Documents


0 download

DESCRIPTION

Practice problems and solutions for intro to computer science.

TRANSCRIPT

Page 1: Computer Science 114 Midterm1 Practice Problem Solutions

CSE114 Midterm 1 - Practice Problem Solutions 1) What is the output of the following statement? System.out.println((2.0 + 3) + 3);

a) 5.03 b) 8.0 c) 8 d) 53 e) 2.033 Even though you are probably used to string concatenation inside of print statements (such as “abc” + x which yields “abcx”), you can still do math inside them. Since there are no strings anywhere in the expression (just numbers), Java adds them up normally. If we were to change the expression to ((2.0 + 3 + “”) + 3), the output would be “5.03”. Java evaluates expressions from left to right, so it would add 2.0 and 3 to produce 5.0 (double + int = double), and once we add the empty string (“”) to it, Java will now interpret it as a string and thus we can no longer do arithmetic with it. Similarly, if the epxression was ((2.0 + “” + 3) + 3), then the output would be “2.033”.

Page 2: Computer Science 114 Midterm1 Practice Problem Solutions

2) What is the output of the following code? for (int c = ‘A’; c < ‘F’; c++)

System.out.print(c + “ ”);

a) A B C D E b) 65 66 67 68 69 c) There is a compiler error. d) None of the above. All information stored on the computer is actually, when in its simplest form, just a number, in binary. So characters, and Strings (which are pretty much just arrays of characters), are all just numbers. Therefore, we can easily initialize an int variable by passing in a character literal. Since we declare “int c =”, Java knows to treat this variable as an integer. Had we written “char c =”, then the answer to the problem would be A. If we want to interpret the integer as a character, we have to cast it, like this:

(char)c However, since we declared c as an integer, we can never actually store it as a character, we can only choose how to interpret it when we use it in expressions.

Page 3: Computer Science 114 Midterm1 Practice Problem Solutions

3) What is the output of the following code? double x = (int)2.0; double f = (x / (int)3.0); System.out.println(f);

a)0 b)0.0 c)0.66 d)0.6666666666666666 e)1 2.0 is a double, and when we cast it to an int, it then becomes 2. However, x represents a double variable, and when we assign 2 to x, Java converts it into 2.0. Then, in the following line of code, since x is a double, even though 3 is casted to an int, we are still doing double division, and 2.0/3 = 0.6666666666666666. If we had casted both sides, ((int) x / (int)3.0), then Java would perform integer division inside the parentheses, (2 / 3 = 0), and then assign that value to f, which is a double, so it would turn it into 0.0. C is incorrect because Java does not automatically round and truncate digits in doubles for you, if you want to print only a certain number of decimals you have to either use String.format() or DecimalFormat (the simplest two options).

Page 4: Computer Science 114 Midterm1 Practice Problem Solutions

4) What is returned by the following method? public static String oneOfTwo()

int x = (6/4 == 1)?2:3; return x;

a)2 b)3 c)”2” d)”3” e)Compiler error. This is a trick question. Pay close attention to the method signature, which states that the method returns a String. x represents an integer variable, and even though we can easily turn it into a String (x + “”), we haven’t done that here and thus this will give a compiler error (Eclipse will underline the return statement in red and you won’t be able to run the program.) If “String” in the method signature was replaced with “int”, then the answer would be A. We use a conditional operator “?” to assign to x one of two values, based on the value of the boolean expression preceding the “?”. 6 / 4 = 1 (not 1.5), because of integer division, and thus the boolean expression is true, and so the conditional expression evaluates to the first choice, not the second one. (bool expression)?if true, return this : otherwise, return this;

Page 5: Computer Science 114 Midterm1 Practice Problem Solutions

5) What is the output of the following program? public class Test

boolean a = false; boolean b = !a; boolean c = (25 % 3 == 0 || 2 != 3);

public static void main(String[]args)

if (a && !a) if(c)

System.out.println(“32”); else System.out.println(“31”);

else if(c || b && a)

if(c) System.out.println(“30”);

else System.out.println(“29”); else System.out.println(“28”);

a)32 b)31 c)30 d)29 e)28 a is false, and b is assigned to !a, meaning “not a”, and is thus true. 25 % 3 = 1, and is not equal to 0, thus 25 % 3 == 0 evaluates to false. However, 2 != 3 evaluates to true, and false || true evaluates to true, therefore c is true. (a && !a) can never be true (logical contradiction), so options 32 and 31 are eliminated immediately. Here’s the tricky part: (c || b && a) evaluates to true, because the && operator has a higher precedence than the || operator (think order of operations), and is thus executed first. (true && false) is false. However, c is true, and (true || false) is true. So we are now inside of the else if block. c is true, so the program prints out 30, and then exits. Notice that the program is written in such a way such

Page 6: Computer Science 114 Midterm1 Practice Problem Solutions

that only one thing is ever printed (try to think of a combination of values for a, b, and c such that more than one thing is printed ­ you won’t be able to :)

Page 7: Computer Science 114 Midterm1 Practice Problem Solutions

6) Write a static public method called encrypt, that takes one String as an argument and returns a String. The method encrypts a word, by replacing each letter with the character two places ahead of it in the alphabet. The last two letters of the alphabet wrap around to the front (i.e. ‘y’ = ‘a’, ‘z’ = ‘b’). Assume that all input consists solely of lowercase letters, and that only one word is input. Sample output: System.out.println(encrypt("abcdefxyz")); cdefghzab System.out.println(encrypt("sampletext")); ucorngvgzv Solution: public static String encrypt(String text) String ans = ""; for (int i = 0; i < text.length(); i++) ans += (char)((((text.charAt(i) ­ 'a') + 2) % 26) + 'a'); return ans; First, we create an empty String ans. This is what we will add on to as we encrypt the text character by character. We cannot simply add two to the character value because we need the last two letters, y and z, to wrap around to a and b. The cheap way to do it would be with two if statements, (if text.charAt(i) == ‘y’), but we’re better than that. In order to wrap around the characters, we will use modulus (%). Let’s say the letter we are encrypting is ‘z’. In order to get its position in the alphabet (0­based), we subtract the code for ‘a’,(‘a’ ­ ‘a’ is 0, ‘b’ ­ ‘a’ is 1, etc.). Next, we add 2. Then, we mod the sum by 26. If the sum is less than 26, then the modulus is equivalent to the sum. If it is greater, then modulus will wrap us around back to 0, and perhaps plus some. Now, our value represents the 0­based position in the alphabet of our new letter. So to get the ASCII value, we simply add back ‘a’. Since we did arithmetic inside of this expression, we have to cast it back to a character by using “(char)” outside of the expression. Now we add it onto ans, and after the loop is finished, we return ans.

Page 8: Computer Science 114 Midterm1 Practice Problem Solutions

7) Write a static public method called reverse, that accepts one String as an argument, returns nothing, and prints the reverse of the input. Sample output: reverse(“The quick brown fox jumps over the lazy dog.”); .god yzal eht revo spmuj xof nworb kciuq ehT Solution: public static void reverse(String input) for (int i = input.length() ­ 1; i >= 0; i­­) System.out.print(input.charAt(i)); This problem is fairly simple, and similar to the previous one, in that we are processing a String character by character, and adding it to output. However, in this case, instead of building a String piece by piece with concatenation, we are instead simply printing to standard output character by character, since our method doesn’t return anything. To print the reverse of the string we simply start at the last character (i = input.length() ­1 ), and keep decrementing i (i­­), until we get to 0 (i >= 0), and print each step of the way, System.out.print(input.charAt(i));. Remember that Strings (just like arrays) are 0­based, so the first character is at position 0. Therefore, in a String of length n, the last character will be at position n­1.

Page 9: Computer Science 114 Midterm1 Practice Problem Solutions

8) Create a class, called TriangleNumbers, that has a static public method called genNum that takes one non-negative integer argument n, and returns the nth triangle number, an integer. The nth triangle number is defined as the sum of numbers 1 through n, inclusive. For example: First triangle number = 1 Third triangle number = 1 + 2 + 3 = 6 Ninth triangle number = 1 + 2 + 3 + ... + 8 + 9 = 45 The program should prompt the user to enter an integer x (you can safely assume it is greater than 0), and then print the first x triangle numbers, with each ith line holding the ith triangle number amount of values, separated by commas (except for the last number in every line). So the first line would contain the first triangle number, the second line would contain the next three, the third line would contain the next six, the fourth line would contain the next ten, and so forth. Sample input/output: User enters 4, program outputs: 1 3, 6, 10 User enters 22, program outputs: 1 3, 6, 10 15, 21, 28, 36, 45, 55 66, 78, 91, 105, 120, 136, 153, 171, 190, 210 231, 253 The solution to this problem is a little more complex, and there is definitely more than one way to do it. Therefore, I have provided two different solutions, which differ in a few ways.

Page 10: Computer Science 114 Midterm1 Practice Problem Solutions

//Author: Vasia //Solution 1 import java.util.Scanner; public class TriangleNumbers /* We could use a for loop to generate the nth triangle number, (which is actually more efficient because multiplication is much more expensive than addition), but it is also acceptable to use the formula for the nth triangle number, as I do here. */ public static int genNum(int n) return (n * (n+1))/2; //main method public static void main(String[]args) //construct a new Scanner Scanner input = new Scanner(System.in); //print out a prompt System.out.println("Triangle Number program. Enter an integer value: "); //read in a value int amount = input.nextInt(); /* totalCount represents the total number of triangle numbers printed perRowCount represents how many we have printed on the current row rowCount represents i, or the number of the row we are currently printing. amountOnThisRow represents how many numbers we want to print on this row, which is equal to the triangleNumber of rowCount, genNum(rowCount). */ int totalCount = 1; int perRowCount = 0; int rowCount = 1;

Page 11: Computer Science 114 Midterm1 Practice Problem Solutions

int amountOnThisRow = genNum(rowCount); /* As you've noticed here, I am missing the first part of the for loop, and I could have easily declared totalCount inside (before the first semicolon), but I declared it earlier so it is easier to see all the variables being used. a while loop could easily be substitued for the for loop: while(totalCount <= amount)

(all the same code, except we add a totalCount++ at the very end.) totalCount++;

*/ for (;totalCount <= amount; totalCount++) //num is the number we are printing int num = genNum(totalCount); System.out.print(num); //we've just printed on a row, so increment the perRowCount perRowCount++; /* lets check if we've printed enough numbers on this row. if so, print a new line, reset the perRowCount, augment the rowCount, and set a new value for amountOnThisRow */ if (perRowCount == amountOnThisRow) System.out.println(); perRowCount = 0; rowCount++; amountOnThisRow = genNum(rowCount);

Page 12: Computer Science 114 Midterm1 Practice Problem Solutions

/* if we can still print more numbers on this line, we need a comma after the number */ else /* unless we are done printing all of the numbers that is, we don't want a comma after the very last number we print. */ if (totalCount != amount) System.out.print(", "); /*finally, print a new line, so that that our output is separated from any subsequent compiler notices. (totally optional) */ System.out.println("");

Page 13: Computer Science 114 Midterm1 Practice Problem Solutions

//Author: Vasia //Solution 2 import java.util.Scanner; public class TriangleNumbers2 /* To calculate the nth triangle number, we need to find the sum of all numbers between 1 and n, inclusive. Create an integer variable ans, and add on to it inside of a loop, iterating from 1, to n. */ public static int genNum(int n) int ans = 0; for (int i = 1; i <= n; i++) ans += i; return ans; public static void main(String[]args) //construct a new Scanner Scanner input = new Scanner(System.in); //print out a prompt System.out.println("Triangle Number program. Enter an integer value: "); //read in a value int amount = input.nextInt(); //separate user input from our output with a new line (optional) System.out.println(""); /* In this solution we will create an array, fill it with triangle numbers, and use it to help us print them in the way we want. Create a new int array called numbers of size amount. amount is the integer that we read in from the user. */ int[] numbers = new int[amount];

Page 14: Computer Science 114 Midterm1 Practice Problem Solutions

/* Fill in the array with triangle numbers, so that the ith position contains the ith triangle numbers (remember arrays are 0 based, so position 0 will hold 0.) */ for (int i = 0; i < amount; i++) numbers[i] = genNum(i); /* Now we have filled up our array. Even though this works just fine, due to the nature of calculating triangle numbers, this is slightly inefficient.(we are doing redundant calculations). Can you think of a more efficient way to fill up the array? (Hint: you might not even have to use genNum.) */ /* row will keep track of what row we are currently printing on perRowCount will keep track of how many we have printed on the currentRow. n is the integer variable with which we will iterate through the array. */ int row = 1; int perRowCount = 0; for (int i = 1; i < amount; i++) //print out the triangle number in the ith position of the array System.out.print(numbers[i]); //increment the perRowCount perRowCount++; /*if we have printed on this row the rowth triangle number amount of triangle numbers (sorry if thats confusing), then we reset the perRowCount, increment the row, and print a new line. */ if (perRowCount == numbers[row]) perRowCount = 0; row++; System.out.println("");

Page 15: Computer Science 114 Midterm1 Practice Problem Solutions

/* if we're not incrementing the row, then that means we're staying on the same row, and we want to print a comma after the number, unless we have printed all of the numbers. since we're only going up to amount ­ 1, as long as i is not equal to amount ­ 1, then we print a comma with a space. */ else if (i != amount­1) System.out.print(", "); //finally, print a new line for good measure (optional) System.out.println("");

Page 16: Computer Science 114 Midterm1 Practice Problem Solutions

9) Write a public static method printHourglass that accepts one integer argument, returns nothing, and prints an hourglass pattern. Sample output: printHourglass(3) *** * *** printHourglass(6) ****** * * ** * * ****** printHourglass(14) ************** * * * * * * * * * * ** * * * * * * * * * * **************

Page 17: Computer Science 114 Midterm1 Practice Problem Solutions

public static void printHourglass(int n) /* n = 1 is a special case, and our code logic only properly works for n >= 2, so we'll just handle this case manually, and then return out of the method. even though our method is void, so it doesn't return anything, we can use the "return;" statement to stop execution and exit the method */ if (n == 1) System.out.println("*"); return; //prints the very top of the hourglass, just a line of n stars. for (int i = 1; i <= n; i++) System.out.print("*"); //print a new line System.out.println("");

//We want the very middle of our hourglass to be //only one line, so we DO NOT

// DO NOT want something like this: // ****** // * * // ** // ** // * * // ****** // //We want something like this: // ****** // * * // ** // * * // ****** //We will only encounter this problem is n is even however, so we'll //handle this by controlling the bounds for the for loop below as //shown. If you want to better understand why I did it this way, //replace the code below (in between the //­­­) with just

Page 18: Computer Science 114 Midterm1 Practice Problem Solutions

//"int bound = n/2 ­ 1;" and then run it with an even number, then an //odd number. //­­­ int bound; if (n % 2 == 0) bound = n/2 ­ 1; else bound = n/2; //­­­ //prints the rest of the top half for (int i = 1; i < bound; i++) //print the initial spaces for (int j = 1; j <= i; j++) System.out.print(" "); //print the star System.out.print("*"); //print the intermediate spaces for (int j = 1; j <= n ­ 2 ­ (2*i); j++) System.out.print(" "); //print the last star, and we can print a newline (println) because //we're done with the line System.out.println("*"); //if n is odd, then we print just one star in the middle of the line, //we need a loop for the spaces beforehand though if (n % 2 != 0) for (int i = 0; i < n/2; i++) System.out.print(" "); System.out.println("*"); //now lets print the bottom half... sigh, the hard part. //PSYCH! its pretty easy, especially because we already wrote //practically all of the code that is going to do it! All we need to //do is take the loop that prints the top half, and flip the for loop //bounds.

Page 19: Computer Science 114 Midterm1 Practice Problem Solutions

//So instead of i ascending, it will now be descending. So, if you //look closely,the two blocks of code are identical, except for whats //inside the for loop header //prints the rest of the bottom half for (int i = n/2 ­ 1; i >= 1; i­­) //print the intial spaces for (int j = 1; j <= i; j++) System.out.print(" "); //print the star System.out.print("*"); //print the intermediate spaces for (int j = 1; j <= n ­ 2 ­ (2*i); j++) System.out.print(" "); //print the last star, and we can print a newline (println) because //we're done with the line System.out.println("*"); //now lets print the very bottom, which is identical to the very top. for (int i = 1; i <= n; i++) System.out.print("*"); //lets print a new line just for good measure (totally optional) System.out.println(""); //we're done! Go nuts, do something like printHourglass(100)! fun fun

Page 20: Computer Science 114 Midterm1 Practice Problem Solutions

10) Problem taken from projecteuler.net (#1) If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. Solution: //Author: Vasia public class PracticeProblemsNumber10 /* Loop through all integers from 3 (because 3 is the first multiple of 3 or 5), to 999, and add them to sum if they are a multiple of 3 (i % 3 == 0) or if they are a multiple of 5 (i % 5 == 0). By far the easiest solution to implement, and to understand. */ public static int firstWay() int sum = 0; for (int i = 3; i < 1000; i++) if (i % 3 == 0 || i % 5 == 0) sum += i; return sum; /* This method is definitely more confusing than the first one. This second solution utilizes two ideas: 1) The formula for the sum of the first n integers. 2) Set inclusion­exclusion principle. The formula for the sum of the first n integers, (1 + 2 + ... + n) is equal to ((n)*(n+1))/2 (I'm sure you all learned this in Calc2.) What if we wanted the sum of (3 + 6 + 9 + ... + 999)? Isn't that just (1 + 2 + 3 +... + 333) * 3 ? Same applies for (5 + 10 + 15 + ... + 995). In order to get the upper bound, we can simply divide 999 by either 3 or 5. 999 / 3 = 333, 999/5 = 199 (integer divison).

Page 21: Computer Science 114 Midterm1 Practice Problem Solutions

However, if the number is a multiple of 3 and of 5, we are accounting for it twice. Therefore, by following the set inclusion­exclusion principle, we simply subtract from our sum the sum of multiples of 15, which is (15 + 30 + 45 + ... + 66). This solution is much more mathematical in nature, and can quite easily be done on paper, and although you aren't expected to come up with this kind of a solution, I provided it here for your enrichment. */ public static int secondWay() int sumOfThrees = 3*(((999/3) * ((999/3) + 1)) / 2); int sumOfFives = 5*(((999/5) * ((999/5) + 1)) / 2); int sumOfFifteens = 15*(((999/15) * ((999/15) + 1)) / 2); return sumOfThrees + sumOfFives ­ sumOfFifteens; /* This third solution is the most efficient of the three as far as spending computational resources go. If you look at the numbers that we are summing up, you can find a simple pattern... 0,3,5,6,9,10,12,15,18,20,21,24,25,27,30... We can get from the very first number to the next number by adding 3, then 2, then 1, then 3, then 1, then 2, then 3, and then the pattern repeats everytime we get to a multiple of 3 and 5 (a multiple of 15). So we can create a little integer array that will store these "addends", and we will cycle through them as we calculate the number we are adding onto our sum. Everytime we figure out the current number, we increment the index we use to keep track of what addend we are currently on, and because we have a small array, we need to mod the increment by the length of the array so that if we incrememnt past its bounds, we wrap back around to 0. (Another way to do this is to check if index == addends.length, then set index to 0.) So before we enter the loop, current is equal to 0. After we enter the loop, after the first few iterations current is equal to 3, then 5, then 6, 9, 10, 12, 15, 18, 20, 21, ... etc. You can put this statement “System.out.println(current);” in the loop to see how current changes with each iteration. */

Page 22: Computer Science 114 Midterm1 Practice Problem Solutions

public static int thirdWay() //0,3,5,6,9,10,12,15 int[] addends = 3,2,1,3,1,2,3; int current = 0; int sum = 0; int index = 0; while (current < 999) current = current + addends[index]; sum += current; index = (index + 1) % addends.length; return sum; /* You can also always cheat and just look it up. However, if you get used to doing this, one day, when you can't find the answer.... You'll be screwed. Also, you can't look up stuff during tests. */ public static int fourthWay() return 223168; //print out the results of the four different solutions //to ensure they are equivalent (what are the odds they are //all wrong? haha) public static void main(String[]args) System.out.println(firstWay()); System.out.println(secondWay()); System.out.println(thirdWay()); System.out.println(fourthWay());