CS99

Fundamental Programming Concepts
Summer 2001

 

Final Exam: Solutions


Tracing Output

int n = 6;
int y = 13;
int d = 1;
while ( y > 0 ) {
       d = (n*y)%7;

       if ( d < 5 )
         y/=2;
      else
         n+=d*y;
}
System.out.println();  

n: 6                   12   17    
y:   13     6   3   1           0
d:     1 1   1   4   6   5   3  

Part 2: Class Definition

class Circle {
   private double radius; // the radius of the circle
   private static final double PI = Math.PI; // constant of the class
   // Default constructor
   Circle( ______________ ) {
      setRadius( 0.0 );
   }

   // Constructor
   Circle ( double r ) {
      setRadius( r );
   }

   // Return the area of the circle
   public double area() {
      return PI*radius*radius;
   }

   // Return the circumference of the circle
   public double circumference() {
      return 2*PI*radius;
   }

   // Assign the radius a new value based on the double parameter.
   // If the parameter is invalid, set the radius to 0.
   public void setRadius( double newRadius ) {
      if ( newRadius >= 0 )
         radius = newRadius;
      else
         radius = 0.0;
   }

   // Return the radius of the circle
   public double getRadius( _______________ ) {
      return radius;
   }

}


TokenReader in = new TokenReader( System.in );
int n = in.readInt();
int i = 1;
while ( i <= n ) {
   int j = 1;
   while ( j <= i ) {
      System.out.print("*");
      j++;
   }
   System.out.print("\t");
   i++;
}


Part 4: Methods

  1. static boolean isPrime( int p ) {
       int factor = 2;
       boolean isPrime = true;
       while ( factor < Math.sqrt( p ) && isPrime ) {
          if ( p%factor == 0 )
             isPrime = false;
          factor++;
       }
      return isPrime && p > 1;
    }
  2. Triangle t = new Triangle( 6, 6, 6 );
    if ( t.isRight() && t.isEquilateral() )
       System.out.println("Wow!");

    BONUS: The message is *not* printed.