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] Give the output of the following code:
    
    char fun(int x);
    
    int main() 
    {
      fun(3);
      cout << "KITTENS" << endl;
      fun(5);
      return 0;
    }
    
    char fun(int x) 
    {
      if (x <= 2) 
      {
        cout << "meow" << endl;
        return 'A';
      } 
      else 
      {
        char letter = fun(x-1);
        cout << letter << " " << x << endl;
        return (letter + 1);
      }
    }
    
    Output:
    
    
  3. [5pts] Consider the following function sum. The function sums integers from start and end. For example, sum(2,5) will return 14, because we have 2+3+4+5 = 14. Fill out the blank.
    
    int sum(int start, int end)
    {
      if( start > end ) 
        return -1;  // error!
    
      if(                )
        return end;
      else
        return start + sum(start+1, end);
    }
    
  4. [75pts] The following program (download hw.cpp) takes an integer as input and calculates the number of spaces needed when it is printed.

    We already wrote a working version.

    
    #include <iostream>
    using namespace std;
    
    int calspace(int num);
    
    int main()
    {
      int n;
      cout << "Integer? ";
      cin >> n;
    
      cout << "#spaces= " << calspace(n) << endl;
      return 0;
    }
    
    
    int calspace(int num)
    {
      int sp = 0;
    
      if( num < 0 )
      {
        sp++;         // +1 for '-' sign
        num = -num;   // make num positive 
      }
    
      // keep dividing num by 10 to calculate #spaces for num
      while( num >= 10 )
      {
        sp++;
        num /= 10;
      }
    
      // +1 to account for the last digit. 
      // For example, calspace(2) should return 1
      return sp+1;
    }
    
    Your Task: Rewrite calcspace! calcspace should be recursive this time. Of course, your new calcspace should be functionally equivalent to the original one. Don't change the main function.

Turn in