CSCI E-50a: Practice Midterm Answer Key
 
HOME | JAVA | RESOURCES | FAQ

ANSWER KEY
1. The effect of the statements
    int m = 9;
    int n = 4;
    m += n;
    n = m - n;
    m = m - n:
    System.out.print (m + "      " + n);
is to produce the output
   
A. 4 9  
B. 5 5  
C. 13 5  
D. 9 4  
E. 13 9  
(A)
We recommend that you make little variable boxes to solve this as Dr. Leitner has shown you in lecture. Then work through the lines of code, updating your variables with each line. We therefore start m at 9, and n at 4. The next line says to add n to m and store it in m, so m becomes 13. In the fourth line, n is set to the result of m - n, so n becomes 9. Finally, m is set to the current value of m minus the current value of n, so 13 - 9 = 4. It's now very easy to see what the print statement will output, and the answer is A. variable boxes

2. The Java statement
      for (int i = 1; i <= 6; i++)
        if ((i <= 4) && (i > 2))
            System.out.print("      " + i);  
will produce the output
A.     1    2    3    4    5    6
B.     2    3    4
C.     1    2    3    4    3     4    5    6
D.     3    4
E.     3
(D) For this question, you may wish to again draw variable boxes to track the values. When you look at code, your goal is to learn to think the way the computer does, and to understand how each line processes. In the code above, the for loop begins with i = 1. Notice that we are using && to test, which "short-circuits" testing - in other words, if the first part of the test is false, the second part is not performed. We therefore test whether 1 <= 4; it is,so we go to the second part of the test. We test whether i > 2; it is not, so we skip over the rest of the if and the loop increments i to 2.
   
We come into the if again -- 2 <= 4 tests true, so we go to the second part, 2 < 2, which is false. The if is skipped, and the loop increments i to 3. We begin the test -- 3 <= 4 is true, so the second part tests, and 3 > 2 is also true. Therefore, the print statement executes, and the number 3 is printed. The loop cycles and i is incremented to 4. When we test, 4 <= 4 is true, and also 4 > 2 is true, so the number 4 is printed. The loop cycles and i is incremented to 5. When we test with 5, 5 <= 4 is false, so the second condition is not tested and the loop cycles again.
   
Since i is always incrementing, you can see logically that no more numbers will be printed. Therefore, the correct answer is D.

3. When people bet on horse races, the racetrack always reduces its payoffs to the largest multiple of 20 cents that does not exceed the exact payoff. This means, for example, that if a payoff was 63 cents, the racetrack would only pay 60 cents.
   
Assuming that the variable payoff is an int variable that holds a number of cents, this reduction could be achieved by the Java statement:
A. payoff = 20 * payoff % 20;
B. payoff = 20 * payoff / 20;
C. payoff = payoff % 20 * 20;
D. payoff = payoff - (int) payoff / 20;
E. payoff = ( payoff / 20) * 20;
(E) If you aren't comfortable working this out through logic, you can approach this problem by taking some examples and trying the formulas. If we take 63, multiply by 20, and then do remainder, we'll get 0; 63 multiplied by 20 and then divided by 20 just returns 63. So neither of these two answers (A or B) can be correct.
   
If we take the remainder of 63 % 20, which is 3, and multiply by 20, we get 60, which would be right (option C). However, if we then try a payoff of 61, get the remainder of 61 % 20, and multiply by 20, our result is 20 - clearly wrong.
   
Option D suggests we do division and 63 / 20 gives us 3 -- the (int) cast is unnecessary, since we're already doing integer division -- and subtracting 3 from 20 gives us 60. However, if we try this with 83 (which should have a payout of 80), 83 / 20 results in 4, and 83 - 4 = 79. Clearly, this doesn't work.
   
Finally, the last choice, to first use integer division to find out how many 20's are in the payoff, then multiplying by 20 to get the amount, fits our tests both logically and arithmetically - 63 / 20 is 3, multiplied by 20 is 60; 83 / 20 is 4, multiplied by 20 is 80. So E is the correct answer.

4. Suppose you are testing a program that accepts as input the profit of a small company and outputs a suggested educational donation for that company according to the following scheme:
   
Negative profit (i.e., a loss) --- $100 donation
Profits less than $100,000 --- 2% of profits, but not less than $200
Profits of $100,000 or more --- $2,000 + 1% of excess over $100,000
   
Which one of the following is the best set of input data for testing this program?
A. All of the following are equally good.
B. 1, 10, 100, 1000, 10000, 100000, 1000000
C. -1000, -100, 0, 1000, 100000
D. -100, 0, 100, 50000, 100000, 200000
E. -100, 0, 1000, 2000, 3000, 100000
(D) You may wish to look at the lecture slides on testing to help with this problem. We want to first consider the categories on the left, which the user will input. Based on the first of these categories, we know we need to test a negative amount, 0, and a positive amount. This immediately knocks out options A and B, since neither requires a negative or 0 test. The next category suggests that we need to test something less than 100000, 100000 itself, and something greater than 100000 - this knocks out options C and E, because neither tests above 100,000. Therefore, the only option left is answer D.
   
If you see a problem like this, you could argue that there are other numbers that should be tested, and you might well be right. However, remember that the question is asking which of the data sets given is the best for testing, so you only need to evaluate those that are listed and find the best among them.
 
5. In a certain prestigious Extension School course, the students receive letter grades based on the following numeric scale:
Numeric Score Letter Grade
93 or above A
from 84 to 92 inclusive B
from 75 to 83 inclusive C
below 75 E
   
Assuming that an int variable score has been assigned a student's numeric score, which of the following Java code segments will correctly assign a letter grade to the char variable named grade?
   
I. if (score >= 93) grade = 'A';
if (score >= 84 && score <= 92) grade = 'B';
if (score >= 75 && score <= 83) grade = 'C';
if (score < 75) grade = 'E';
II. if (score >= 93) grade = 'A';
if (84 <= score <= 92) grade = 'B';
if (75 <= score <= 83) grade = 'C';
if (score < 75) grade = 'E';
III. if (score >= 93) grade = 'A';
else if (score >= 84) grade = 'B';
else if (score >= 75) grade = 'C';
else grade = 'E';
   
A. II only
B. III only
C. I and II only
D. I and III only
E. I, II, and III
(D) A reading of the three code fragments above should tell you immediately that number II is impossible - it has syntax that is not legal in Java (e.g., 84 <= score <= 92). This leaves number I and number III; it also eliminates choices A, C, and E.
   
Therefore, you need to decide whether only III will work, or whether I and III will both work. So the question is regarding fragment I. When you compare it to the starting table, you can see that the breakdown is correct. Each of the if statements has a compound condition using &&, which means that it will set the variable grade only when both of its tests are true. You can therefore expect that although more overall tests will be done, the variable will not be set incorrectly. Therefore, either segment I or III will perform correctly, and the answer is D.
 
6. The following Java program is supposed to print the design

     .  .  *  .  .
     .  *  *  *  .
     *  *  *  *  *
     .  *  *  *  .
     .  .  *  .  .
Unfortunately, this program contains some errors -- find and correct 7 distinct ones!
    class Prob6
    {
        public static void main
        {
            final char STAR = '*';
            final char  DOT = ".";
        
            for (i = 1; i < 5; i++)
            {
                for (int j = 1; j <= 5; j++)
                    if ( (i-3) * (i-3) + (j-3) * (j-3)) < 5
                        System.out.print(  STAR  );
                    else System.out.print( "  " + DOT );
            }
        }
    }
 
    OK, let's see if we can list the errors... You may want to count braces and parens, but unless you're told to do so you should not consider them errors unless the compiler would complain about them.
       
    1. ( String [ ] args ) is missing next to main
    2. DOT is assigned to a String, but its type is a char - it should be set equal to '.'
    3. The type for the counter i is not declared; it should be written as int i.
    4. There are 5 rows in the picture, so the loop with i needs to run 5 times; therefore it should test i <= 5.
    5. In the if statement, the closing paren is before the conclusion of the statement - move it outside the 5 so that it reads if ( (i-3) * (i-3) + (j-3) * (j-3) < 5 ) ...
    6. In the if/else, the STAR is printed without accompanying space, although space shows in the picture above - add the space shown with printing DOT also to the printing for STAR.
    7. As written, everything will be printed on one line - at no point is there a newline printed. In the picture, we need a newline each time the row changes, so add a System.out.println() statement after the inner for loop.
          
    We realize that you were told to use curly braces, and there are times they are omitted in the code above. However, while we DO want you to use them, they are a style issue rather than an error, so they would not count in the errors above.
 
7. A prime number is an integer > 1 that has no divisors (except for 1 and the number itself). For example, 5 and 7 are both prime, but 9 is not
(since 3 divides evenly into 9).
   
Write a Java program that prints out all of the prime numbers between 101 and 201, inclusive.
  You will want to think about the algorithm to use for this program, before you begin to code it. You are told that a prime number has no divisors, and you know that when a number is a divisor of another number, you have a remainder of 0 - it divides in evenly. So we can test a specific number by trying to divide it by all the numbers from 2 up, to look for remainders of 0 and see if any of them divides into it. We also need a way to keep track of whether or not there are any divisors, and the easiest way to do this (given what you know so far) is to simply count them. If we test all possible divisors and the count remains 0, we have a prime number.
   
To test for divisors, we'll need a loop, so we can go through from 2 up to the number itself. We'll also need a loop to go from 101 to 201, so we can cover all of the numbers we need to check. This means we'll end up with a program similar to the following:
   
class Prime
{
    public static void main( String [] args )
    {
        int count = 0;   //  variable to count the number of divisors
    
        //  the first loop will go through the numbers we've been asked to test...
        for( int i = 101; i <= 201; i++ ) {
   
            //  the second loop will look for divisors, going from 2 to the number being checked
            for( int j = 2; j < i; j++ ) {
                //  Look for a quotient of 0 - if so, we have a divisor and we count it
                if( i % j == 0 ) {
                   count++;
                }
            }  //  ends inner loop doing divisors
   
            //  Now we need to see if we counted any divisors; if not, we have a prime!
            if ( count == 0 ) {
		        System.out.println( i + " is a prime number." );
            }
            
            //  Finally, we reset the counter to 0 before we go on the the next number
            count = 0;
        }  //  closes outer for loop going through the numbers from 101 - 201
    }      
}
   

HOME | JAVA | RESOURCES | FAQ

© 2009, The President and Fellows of Harvard College
Please send comments to The Webmaster
URL: http://www.fas.harvard.edu/~libe50a/practicemidterm.html
Last modified: Saturday, 24-Oct-2009 20:09:23 EDT