Computer Science 2310
Spring 2005
Practice questions for quiz 2

This will be a closed book quiz. You may bring one 8.5x11 page of prepared notes, written on both sides.

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

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

    Answer:______________________________________________

  2. Write a recursive public static method anySevens(n) in Java that 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.

  3. Suppose that array A contains the following.

        i      A[i]
        0       3
        1       7
        2       8
        3       5
    
    Function mystery is shown below. Starting with A holding what is shown above, what is in array A after running mystery(A,4)?
       public static int mystery(int[] B, int n)
       {
         int k;
         for(k = 0; k < n; k++) 
         {
           B[k] = B[k] + k;
         }
       }
    

  4. What are in array A after running the following Java program fragment? Be careful.

        int[] A = new int[4];
        int k;
        for(k = 0; k < 4; k++) A[k] = k+1;
        for(k = 0; k < 3; k++) A[k+1] = A[k] - 1;
    

  5. What is the difference between the logical and physical size of an array?

  6. Write a public static Java method that computes the sum of all of the numbers in an array of integers. There should be two parameters, the array A and the logical size n of the array. Only compute the sum up to the logical size. Use a loop for this function. A heading for this function is shown.

      public static int sum(int[] A, int n)
    

  7. Write a definition of sum that has the same meaning as in the preceding question, but use recursion for this definition instead of a loop.

      public static int sum(int[] A, int n)
    

  8. You would like to set variable s to the sum of all of the integers in array Fish, which has 12 members. What statement would you write to use function sum to do the computation?

  9. Suppose that s and t are two variables of type String. Write a Java expression that yields true just when s and t hold the same string. (For this question, two strings are the same if they have exactly the same characters, in the same order.)