CPSC 124, Fall 2021: Sample Answers to Quiz #5

These are sample answers only.

Question 1. What is the effect of making a subroutine private?

Answer. The subroutine can be called only in the same class where it is defined, not from other classes.

Question 2. State two different reasons for using named constants such as static final double INTEREST_RATE = 0.025;

Answer.  a)  It makes the program easier to read and understand, since a name can be more meaningful than a constant value.

b)  If the value needs to be changed, it only has to be changed in one place, in the declaration, not every place the constant value is used.

Question 3. The subroutine stars(n) prints out a line of n asterisks, where n is a parameter of type int. Write a code segment that will use this subroutine to produce the output shown here:

           *
           **
           ***
           ****
           *****
           ******

Answer.

       for (int i = 1; i <= 6; i++) {
           stars(i);
       }
       
also acceptable:

      stars(1);
      stars(2);
      stars(3);
      stars(4);
      stars(5);
      stars(6);

Question 4. Write a static subroutine named sameParity with a return type of boolean and two parameters of type int. The return value should be true if both parameters are even or if both parameters are odd. The return value should be false if one parameter is even and the other is odd. Recall that an integer N is even if N % 2 == 0. You get a lot of the points for this problem by getting the first line of the subroutine definition correct

Answer.

     static boolean sameParity( int a, int b ) {
         if ( (a % 2) == (b % 2) ) {
             return true;
         } 
         else {
             return false;
         }
     }
     
or less elegantly,

     static boolean sameParity( int a, int b ) {
         if ( ((a % 2 == 0) && (b % 2 == 0))
                   ||  ((a % 2 == 1) && (b % 2 == 1)) ) {
             return true;
         } 
         else {
             return false;
         }
     }

or more elegantly,

     static boolean sameParity( int a, int b ) {
         return (a % 2) == (b % 2);
     }

or maybe most elegantly,

     static boolean sameParity( int a, int b ) {
         return  (a + b) % 2 == 0;
     }