Name: ____________________________________________________ Alpha: _____________________

Describe help received: _________________________________________________________________

  1. [10 pts] We would like you to self-test how much you retained from the lecture. Write the correct solution to the Mandatory Practice Problems. Debug your code until it runs correctly. Circle below how you wrote your code.
    1. (10 pts) I was able to write the code without referring to anything.
    2. (10 pts) I had to look at the notes, but still I was able to write the code without looking at the solution.
    3. (10 pts) I had to look at solutions to finish to code.
    4. (0 pts) I didn't do this.
    If you had to look at the solution, briefly describe what you missed but understand now.
    
    
    
    
  2. [10pts] Consider the following recursive function:
    
    void toy(int n) 
    {
      if (n == 0) 
      { 
        cout << "B"; 
      }
      else
      {
        cout << "A"; 
        toy(n - 1); 
        cout << "C"
      }
    }
    
    1. [2pts] Circle the base case with label B.
    2. [2pts] Circle the recursive case with label R.
    3. [2pts] What output would the call toy(0) lead to?
      
        
    4. [2pts] What output would the call toy(1) lead to?
      
        
    5. [2pts] What output would the call toy(2) lead to?
      
        
  3. [10pts] Give a recursive definition of a function harm(n) which computes the sum of the first n terms in the harmonic series: \[\frac{1}{1} + \frac{1}{2} + \frac{1}{3} + \frac{1}{4} + \cdots + \frac{1}{n}\] For example, harm(1) should return 1, and harm(2) should return 1.5.

    Warning: Be careful about the type of an expression. For example, 1/3 evaluates to 0 of type int!

    
    
    
  4. [70pts] Give a recursive function pow(x,n) that calculates x^n (i.e., x to the power of n). For example pow(2, 5) should return 32, and pow(3, 4) should return 81. No loops!
    ~/$ ./hw
    Enter x and n: 3.6  7
    x^n is 7836.42
    
    
    #include <iostream>
    using namespace std;
    
    double pow(double, int);
    
    int main() 
    {
      double x;
      int n;
      cout << "Enter x and n: ";
      cin >> x >> n;
      cout << "x^n is " << pow(x,n) << endl;
      return 0;
    }
    
    // Define pow: it must be recursive!
    

Turn in