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] Suppose we want to read an array size from user, but worry about the user entering 0 or a negative number. Consider the three code snippets below and answer the questions below them.
    
    int n;
    cin >> n;
    double* Z;
    Z = new double[n];
    if (n <= 0) {
      cout << "Error!" << endl;
      Z = new double[10];
    }
    
    Z[0] = 5;
    
    
    int n;
    cin >> n;
    if (n <= 0){
      cout << "Error!" << endl;
      double* Z = new double[10];
    }
    else
      double* Z = new double[n];
    
    Z[0] = 5;
    
    
    int n;
    cin >> n;
    double* Z;
    if (n <= 0){
      cout << "Error!" << endl;
      Z = new double[10];
    }
    else
      Z = new double[n];
    
    Z[0] = 5;
    
    circle one:
    • compile-time error
    • possible run-time error
    • OK
    If error, why?
    circle one:
    • compile-time error
    • possible run-time error
    • OK
    If error, why?
    circle one:
    • compile-time error
    • possible run-time error
    • OK
    If error, why?
  3. [10pts] The program toy.cpp listed below is intended to work as follows: For example, given the following input from the terminal
      5 
      1.1 -1.3 4 -7.4 -3.6 
    ... the program should output the following:
      Negatives in reverse:
      -3.6
      -7.4 
      -1.3 
    However, the program doesn't work as it is intended to. Fix the bugs by annotating in the code directly. (Hint: There are 6 bugs).

    Note: A similar question will appear in the exam. Try to solve the problem by hand (and then double-check your answer by compiling and running your solution).

    
    // fix the bugs!!
     1 #include <iostream>
     2 using namespace std;
     3
     4 void print_negatives(double* A, int N);
     5
     6 int main()
     7 {
     8   int N=0;
     9   double* A = new double[N];
    10   cin >> N;
    11
    12   for(int i=0; i<N; i++)
    13     cin >> A[N];
    14
    15   cout << "Negatives in reverse:" << endl;
    16
    17   void print_negatives(double* A, int N);
    18
    19   delete [] A;
    20
    21   return 0;
    22 }
    23
    24 void print_negatives(int* A, int N)
    25 {
    26   for(int i = N; i >= 0; i--)
    27     cout << A[i] << endl;
    28 }
    
Bring to class