
     CSc 17  Test 1   Wednesday  18 October 2000
    >>>>>>>>>>>>>>SUGGESTED ANSWERS<<<<<<<<<<<<<<<<<<<<<<<<<<
1. (12 pts) Assume the statement
  if(x<y) if(x<5) cout<<'D'; else if(x>77) cout<<'A'; else cout<<'B';
 is preceded by one of the four pairs of statements below.  State the output
 that occurs for each pair
  a) x=61; y=8;    <no output>
  b) x=4; y=7;     D
  c) x=50; y=60;   B
  d) x=80; y=90;   A
2. (8 pts)  State the output of the following code.
   char *ch="Hello";
   ch[2]='\0';
   cout<<(2+4*5%6)<<endl;          4
   cout<<(2+3/4/5.0)<<endl;       2
   if(!(2>3) && 4==4)
     cout<<'A'<<endl;              A
   else
     cout<<'B'<<endl;
   cout<<ch<<endl;                 He
3. (12 pts) State the output of the following main program.
  void func(int a, int &b, int &c, int *d, int *&e){
    d=&c;
    e=&b;
    a++;
    b+=a;
    c+=b;
    cout<<a<<" "<<b<<" "<<c<<endl;
  }
  void main(){
    int x,y,z, *tPt,*vPt;
    x=1;
    y=5;
    z=10;
    tPt=&y;
    vPt=&x;
    func(x,y,z,tPt,vPt);                  2 7 17
    cout<<x<<" "<<y<<" "<<z<<endl;        1 7 17
    x=10; y=20;
    func(x,x,x,tPt,vPt);                  11 42 42
    cout<<x<<" "<<*tPt<<" "<<*vPt<<endl;  42 42 42
  }
4. (25 pts) Write a recursive function, sum(), which computes the sum of the
 elements of an array of ints using the following algorithm:  to sum the
 elements a[low] through a[high], inclusive, add a[low] and a[high] to the
 sum of the elements between a[low] and a[high] (excluding a[low] and
 a[high]).  In particular, if we have int a[100]; the call to sum the
 elements a[0] to a[30], inclusive, should be sum(0,30,a);, and this call
 should return the sum.
 int sum(int low, int high,int a[]){
   if(high<low)
      return 0;
   else if(low==high)
          return a[low];
        else
          return a[low]+a[high]+sum(low+1,high-1,a);
  }
5. (18 pts) I forgot to document the following function. Provide it.
   //Purpose: Find the maximum of the entries a[low-1]...a[high]
   //Pre-conditions:  low<=high+1 (else infinite loop)
   //Post-conditions: return the maximum
   int xxx(int low, int high,int a[]){
     int y;
     y=a[low-1];
     while(low!=high+1){
       if(a[low]>y)
         y=a[low];
       low++;
     }
     return y;
   }
6. (25 pts) Add to the class A below declarations of the copy constructor
and the member function getX() which returns the value of x so that the
following code will compile:
     A a, b(a);
     cout<<b.getX()<<endl;

  class A{
    public:
       A();
       void set(int a);
          A(const A&c);    //added as part of answer
          int getX();      //added as part of answer
    private:
       int x;
  };

  State the declarations, indicate where they appear in the declaration of
  A above, and then provide the definitions of the two functions below.

   A::A(const A&c){
      x=c.x;
   }
   int A::getX(){
      return x;
   }

