CSCI 2310
Fall 2009
Exercises for Quiz 5

  1. What is the value of mystery(4)?

    	public static int mystery(int n)
    	{
    	  if(n == 1) return 1;
    	  else return 3*mystery(n-1);
    	}
    

    Answer

  2. What is the value of strange(4)?

    	public static int strange(int n)
    	{
    	  if(n == 0) return 2;
    	  else return strange(n-1) + 3;
    	}
    

    Answer

  3. Write a Java definition of public static method abs(x), taking a value x of type double and producing its absolute value.

    Answer

  4. Write a Java definition of public static method fourthroot(x), taking a value x of type double and producing its fourth root value. You can use function sqrt(x), which computes the square root of x. The fourth root of x is the square root of the square root of x.

    Answer

  5. Using recursion, and not a loop, write a Java definition of public static method sum(n) = 1 + 2 + ... + n. (Hint. Notice that sum(1) = 1. Also notice that, for n > 1, sum(n) = sum(n-1) + n.)

    Answer

  6. Using recursion and not a loop, write a public static method anySevens(n) in Java that takes an integer parameter n and returns 1 if there are any 7's in the decimal representation of n, and 0 otherwise. For example, anySevens(974) = 1, anySevens(7) = 1 and anySevens(32) = 0. Function anySevens should require its parameter n to be nonnegative. For this problem, do not use any form of loop, and do not alter the value of any variable that already has a meaningful value.

    Hint. You can get the rightmost digit of n by computing n % 10. You can get all but the rightmost digit by computing n/10. For example, if n is 1974 then n % 10 is 4 and n/10 is 197. Notice the following facts.

    1. anysevens(0) is false.
    2. If n % 10 = 7, anysevens(n) = true. For example, anysevens(47) = true because the rightmost digit of 47 is 7.
    3. If n is not 0 and n % 10 is not 7 then anysevens(n) is the same as anysevens(n/10). For example, anysevens(1974) = anysevens(197).

    Answer