Name: ____________________________________________________ Alpha: _____________ Section: ________

Describe help received: _________________________________________________________________

See the bottom for how to submit your work.

Due: Before 0800 on next class day

  1. (10 pts) Read today's lecture notes. Honestly declare how you read the notes.
    1. (10 pts) I read the notes carefully. I have a good understanding of the topics therein.
    2. (10 pts) I read the notes carefully, but I don't really understand the following points well:
      
      
      
    3. (0 pts) I didn't read the notes carefully.
  2. [10pts] Write a recursive function that sums all the values in the list.
    The definition of Node is given as follows:
    
    struct Node
    {
      double data;
      Node* next;
    };
    
    The iteration version of the function is as follows:
    
    double sum(Node* L)
    {
       double total = 0;
       for(Node* t = L; t != NULL; t = t->next)
         total += t->data;
    
       return total;
    }
    
    // Give a recursive definition:
    
    Sample runs (user input in red):
    ~/$ ./hw
    Integer? 0
    #spaces= 1
    
    ~/$ ./hw
    Integer? -1
    #spaces= 2
    
    ~/$ ./hw
    Integer? 100
    #spaces= 3
    
    ~/$ ./hw
    Integer? -5938
    #spaces= 5
    
  3. [80pts] 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.

Submit to the submission server (due: 0800 on the next class day)

~/bin/submit -c=IC210 -p=hw36 hw.cpp
Bring to class