Computer Science 2610

Spring 2000

Quiz 2

 

This is a closed book quiz.  You may use one sheet of prepared notes, written on both sides.  Give the best answer that you can to each question.  You have 25 minutes.  Class will resume after the quiz.

 

1. Which of the following is an invariant for the loop in function one?  Remember to check all values that the variables take on at the top of the loop.

 

  (a) m = 17 - 4n

  (b) m = m + 4

  (c) n > 0

  (d) n = m - 2

 

      int one()

       {

         int n,m;

         n = 3;

         m = 5;

         while(n > 0) {

           n = n - 1;

           m = m + 4;

         }

         return m;

       }

 

2. What is the value of mystery(3)?

 

  (a) 1

  (b) 3

  (c) 4

  (d) 8

 

       int mystery(int n)

       {

         if(n == 0) return 1;

         else return mystery(n-1) + mystery(n-1);

       }

 

 


3. What is printed by function two when it is run?

 

      void help(int a, int &b)

      {

        b = a + 1;

        a = a * 2;

      }

 

      void two()

      {

        int a = 5;

        int s = 14;

        int t = 94;

        help(s,t);

        cout << “a = “ << a

             << “ s = “ << s

             << “ t = “ << t << endl;

      }

 

Answer: ________________________________________                    

 

 

4. Write a recursive function called numfives so that numfives(n) that returns the number of 5’s in the decimal representation of n.  For example, numfives(35251) = 2, numfives(45) = 1 and numfives(0) = 0.  Assume that n is nonnegative.

 

Note that you can get the rightmost digit of a number n by taking the remainder when you divide n by 10, and you can remove the rightmost digit by dividing n by 10.

 

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.

 

       int numfives(long n)