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) NOTE: This problem is using an operator ( && ) that we have not learned yet, and you do NOT need to know it for our midterm!! The && operator has the ability to combine conditions and test whether both of them are true at the same time. We'll talk about it in class in a couple of weeks.

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 will test two conditions to get an overall true or false result. We therefore test whether 1 <= 4; it is. We then 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, and we go to the second part, 2 < 2, which is false. The if block is skipped, and the loop increments i to 3. We begin the test -- 3 <= 4 is true, and 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 nothing prints 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. Consider
     class Prob4
     {
         static void silly ()
         {
               int temp = x;   x *= y;   y = temp;
         }
         
         public static void main( String [] args )
         {
               int x = 3;     int y = 4;
               silly();
         }
     }
What will be the output of this program?
A This code will not even compile!
B 4
C 3
D 12
E An error will occur at execution time!
(A) The correct answer is A - the code will not compile. If you look at the method named 'silly()', you will see three variables used there; however, only one of them, temp, is declared in the method, and the method has no parameters. In main, int x and int y are declared, but they are local to main, and are not visible to the method. Therefore, none of the numeric answers is correct, and since the code does not compile, it also cannot be executed (i.e, it can't be run using 'java Prob4').
 
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) NOTE: This problem also uses the && operator - you will not be expected to know this for the midterm.
  
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 only consider them errors when the compiler would complain about them.
       
    1. ( String [ ] args ) is missing next to main
    2. DOT has its type declared as a char, but is assigned to a String - 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
                         //  Note - we could also add up divisors and test the sum = 0
    
        //  the first loop will go through the numbers we've been asked to test...
        for( int number = 101; number <= 201; number++ ) {
   
            //  the second loop will look for divisors, going from 2 to the number being checked
            //  We really only need to test divisors up through the number/2, but going through them
            //  all is fine on the test...
            for( int divisor = 2; divisor < number; divisor++ ) {
 
                //  Look for a quotient of 0 - if so, we have a divisor and we count it
                if( number % divisor == 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( number + " 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

© 2010, The President and Fellows of Harvard College
Please send comments to The Webmaster
URL: http://www.fas.harvard.edu/~libe50a/practicemidterm.html
Last modified: Friday, 21-Oct-2011 12:57:19 EDT