CSCI 2310
Fall 2009
Exercises for Quiz 4

  1. A method contract

    1. tells why the method was written, and where it fits into the overall program.
    2. tells how the method works, and what its local variables are used for.
    3. tells what the method accomplishes and how its parameters affect what it accomplishes.
    4. tells all of the above things.

    Answer

  2. Lab 3 describes numbers called Carmichael numbers. (A Carmichael number is always a positive integer.) Suppose that you already have a function, isCarmichael(n), the returns true if n is a Carmichael number and false if not. Write a Java method called nextCarmichael(m), which returns the smallest Carmichael number that is strictly greater than m. Use isCarmichael.

    Answer

  3. Write a Java method sum(a,b) that returns a + (a+1) + ... + b. For example, sum(5,8) = 5 + 6 + 7 + 8 = 26. Assume that a and b are integers.

    Answer

  4. The mean of three numbers is their sum divided by 3. Write a static method mean(x,y,z) that returns the mean of x, y and z, using the following heading.

      public static double mean(double x, double y, double z)
    

    Answer

  5. The geometric mean of two numbers x and y is the square root of the product of x and y. Write a static Java method called geometricMean that returns the geometric mean of its two parameters. Note. You can use function Math.sqrt to compute square roots. Math.sqrt(x) is the square root of x.

          public static double geometricMean(double x, double y)  
    
    

    Answer

  6. Using method geometricMean from the previous exercise, write a program fragment that sets variable z to the geometric mean of variable r and twice variable s. Assume that r and s have type double.

    Answer

  7. Static method f is defined as follows.

         public static int f(int x)
         {
           int k = 1;
           while(k <= x) {
             k = k + k;
           }
           return k;
         }
    
    What are f(3) and f(f(3))?
       f(3)    = _________
    
    
       f(f(3)) = _________
    
    

    Answer