CSCI 2310
Fall 2009
Exercises for Quiz 6

  1. 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;
         }
       }
    

    Answer

  2. 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;
    

    Answer

  3. 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)
    

    Answer

  4. 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)
    

    Answer

  5. You would like to set variable s to the sum of all of the integers in array Fish. What statement would you write to use function sum to do the computation?

    Answer

  6. Suppose that s and t are two variables of type char[]. That is, each is an array of characters. Write a definition of function equal(s, t) that returns true if arrays s and t have the same length and contain the same characters, in the same order.

    Answer