CS 99

Summer 2001                                                                               8.01

 

 


Solutions for Final Exam Sample Questions

  

Methods

 

1.       Write a method that takes an integer value and returns the number with its digits reversed.  For instance, given the number 7631, the method should return 1367.  If the number ends in a 0, or several zeros, the method should return a number shorter than the original. So if the user enters 3290, the method will return 923.

NOTE: This is way way harder than anything you’ll see on the exam.
Solution
/* Returns a number whose digits are the reverse of the parameter n */
static int reverse( int n ) {
    int rev = 0; // number which will have the reversed digits
    int digit; // next digit to add
    int length = (int) (Math.log( n )/Math.log(10)) + 1; // number of digits in n
    int count = 0; // counter variable
    while ( count < length ) {
        //digit gets value of ‘count+1’ digit in n
        // i.e., if count = 0, digit gets the ‘first’ digit in n
        digit = (int) (n/Math.pow( 10, length-count ))%10;
        // add digit to ‘back’ of variable rev, giving it the proper power of 10
        rev += Math.pow( 10, count )*digit;
        count++;
    }
    return rev;
}

2.       Write a method that accepts a String and returns the number of punctuated sentences contained within it. For the purposes of this method, a punctuated sentence is one that ends in a period, question mark, or exclamation point.

Solution
// return the number of punctuated sentences in String s
static int numOfSentences( String s ) {
   int num = 0; // number of sentences
   int k = s.length() – 1; // counter variable
   while (k >= 0 ) {
       // if we see a sentence closing character, add 1 to num
       if (s.charAt( k )==’?’ || s.charAt( k ) == ‘!’ || s.charAt( k ) == ‘.’ )
            num++;
       k--;
   }
   return num;
}

 

 

3.       Recall that a "perfect" number equals the sum of its divisors, including 1 but excluding itself.  Complete the implementation of the static boolean method isPerfect below.

Solution
// return true if p is a "perfect" number; false otherwise
static boolean isPerfect( int p ){
    int factor = 1;     // candidate factor and counter variable
    int sum = 0;      // current sum of divisors of p
    while ( factor < p ) {
        // if factor divides p, add it to sum
        if ( p%factor == 0 )
             sum+=factor;
        factor++;
    }
    return sum == p;
}

 

4.       Write a method the accepts a String and returns the length of the longest word contained within it.

Solution
// return longest word in String s
static int longestWord( String s ) {
   int longest = 0; // length of longest word so far
   int latest = 0;     // length of current word
   int j = 0;            // counter variable
   while ( j < s.length() ) {
       // if we see character that indicates end of word, update longest and latest appropriately
       if ( s.charAt( j ) == ‘ ‘ || s.charAt( j ) == ‘.’ || s.charAt( j ) == ‘!’ || s.charAt( j ) == ‘?’ ) {
            if ( latest > longest )
                 longest = latest;
            latest = 0;
       }
       else // haven’t seen end of current word, so update latest to indicate length
            latest++;
       j++;
   }
   return longest;
}

 

5.       Write a static method consec( int n ) that returns true if the four consecutive integers starting with n are divisible by 5, 7, 9, and 11 respectively.

Solution
// Returns true if the four consecutive integers starting with n are divisible by 5, 7, 9, 11
// respectively
static boolean consec( int n ) {
   return ( n%5 == 0 ) && ((n+1)%7==0) &&((n+2)%9==0)&&((n+3)%11==0);
}

 

 

Tracing loops

 

6.       Trace the sequence of assignments to the variables made by the program segment given below.  The first three assignments have been done for you.  You may not need all the columns provided.

int n = 57;
int x = 0;
int y = 1;
while ( n != 0 )

          if ( n%2 != 0 )
              n = n/3;

     else {
              n = n + 1;
              x *= 9;
              y += 10; 
          }

n:

57

 

 

19

6

7

 

 

2

3

 

 

1

0

x:

 

0

 

 

 

 

0

 

 

 

0

 

 

 

y:

 

 

1

 

 

 

 

11

 

 

 

21

 

 

 

 

 

7.       Trace the sequence of assignments to the variables made by the program segment given below.  You may not need each column. 

int p = 32;
int d = 3;
int n = 5;
while ( n < 10 ) {

          p = 32/d;

          do {
              if ( n%d > 1 )
                   n++;
          } while ( n%d != 0 );

d*=2;
}

p:

32

 

 

10

 

 

5

 

2

 

 

 

 

 

 

 

 

 

d:

 

3

 

 

 

6

 

12

 

 

 

 

 

 

 

24

 

 

n:

 

 

5

 

6

 

 

 

 

7

8

9

10

11

12

 

 

 

 

 

Classes & Objects

 

8.       Fill in the blanks and methods in the class below.

Solution
class Rectangle {

   
private int length, width;

    // Default constructor

          Rectangle ( _______________ ) {
             
length = width = 0;
          }

          // Constructor
         
Rectangle ( int l, int w ) {
             
length = l;  width = w;
          }

          public
int area() {
             
return length * width;
          }

 

          public int perimeter() {
             
return 2*(length + width);
          }

          public
void setLength( int l ) {
             
if ( l > 0 )
               length = l;
           else
               length  = 0;
          }

          public
void setWidth( int w ) {
             
if ( w > 0 )
               width = w;
           else
               width = 0;
          }

 

          public int getLength( ______________ ) {
             
return length;
          }

          public
int getWidth( ________________ ) {
             
return width;
          }


     }

 

9.       Write code to do the following.  Name the variables whatever you would like.

1. Create a TokenReader object to read in input from the keyboard.
2. Read in 2 integer input values from the user and use those values to instantiate a
     Rectangle with the width as the first value and the length as the second.
3. Create a new Triangle object with sides 9, 9, 9.
4. Print out the perimeter of the rectangle if its area is greater than the triangle's.

TokenReader in = new TokenReader( System.in );
int val1 = in.readInt();
int val2 = in.readInt();
Rectangle r = new Rectangle( val1, val2 );
Triangle t = new Triangle( 9, 9, 9 );
if ( r.area() > t.area() )
   System.out.println( r.perimeter() );


 

Star Patterns

 

Use only the following types of print statements in the questions below.

10.   Write a program segment that reads in the size of a square and then prints a square of that size out of asterisks with a diagonal line across the middle.  So if your program takes in an input of 5, it should print:

* * * * *
* *      *
*   *    *
*     *  *
* * * * *
Solution 1
int n = in.readInt();
while ( row < = n ) {
    int col = 1;
    while( col < = n ) {
        if ( row == 1 || row == n || col == 1 || col == n || col == row )
             System.out.print( “*” );
        else
             System.out.print( “ “ );
        col++;
    }
    System.out.println();
    row++;
}

Solution 2
int n = in.readInt();
while ( row < = n ) {
    int col = 1;
    if ( row == 1 || row == n )
        while ( col <= n ) {
             System.out.print( “*” );
             col++;
        }

 
   else
        while ( col <= n ) {
             if ( col == 1 || col == n || col == row )
                  System.out.print( “*” );
             else
                  System.out.print(“ “ );
             col++;
        }

    System.out.println();
    row++;
}

11.   Write a program segment that reads in a non-negative integer n and a triangle alternating  asterisks and @’s on each line.  Hence, if the program takes in an input of 6, the following pattern should be printed:

*
@@
***
@@@@
****
@@@@@
******

Solution
int n = in.readInt();
while ( row < = n ) {
    int col = 1;
    while( col < = row ) {
        if ( row %2 == 1 )
             System.out.print( “*” );
        else
             System.out.print( “@“ );
        col++;
    }
    System.out.println();
    row++;
}

12.   Write a program segment that reads in a non-negative integer n and prints a checkerboard pattern with @’s and asterisks.  If the program takes in as input 3, it will print the following pattern:

@*@
*@*
@*@

Solution
int n = in.readInt();
while ( row < = n ) {
    int col = 1;
    while( col < = n ) {
        if ( (row+col) %2 == 1 )
             System.out.print( “*” );
        else
             System.out.print( “@“ );
        col++;
    }
    System.out.println();
    row++;
}