SOLUTIONS TO MARCH 8th HOMEWORK

PART ONE:

 
(set cdr* (mapc cdr)) 
(set append (lambda(l1 l2) ( (combine l2 cons (lambda(x) x)) l1)))
(set addtoend(lambda(x l) ( (combine (cons x '()) cons (lambda(x) x)) l)))
(set reverse (combine '() addtoend (lambda(x) x)))
(set mkpairfn(lambda(x) (mapc (lambda(l) (cons x l)))))

PART TWO:
pages 285-286:

  9.   i:=0; 
       found := false; 
       while (i< listlen) and (not found) do 
        begin 
           i := i+1; 
           found := list[i]=key;          
        end; 
  

14.(a) SUM1 = 46, SUM2 = 48

14.(b) SUM1 = 48, SUM2 = 46

15. When I typed in and ran the program, sum1 got 48 and so did sum2.
The program appears below:


int fun(int *k); int fun(int *k) { *k += 4; return 3 * (*k) - 1; } int main() { int i=10, j=10, sum1, sum2; sum1 = (i/2) + fun(&i); sum2 = fun(&j) + (j/2); cout << sum1 << " " << sum2 << endl; return 0; }
What happened apparently is that Codewarrior C++ did a right-to-left evaluation of the expression (i/2) + fun(&i) and then a left-to- right evaluation of the expression fun(&j) + (j/2).

So the rule may have been that if there is one function invocation appearing as part of an expression, the function invocation is done before anything else.

 21.(a) 7

 21.(b) 12 

pages 325-327:

12.(a)

 case k of
   1,2: j := 2*k-1;
   3,5: j := 3*k+1;
   4:    j := 4*k-1;
   6,7,8: j:= k-2;
end;

12.(d)

switch (k) {
   case 1: case 2:  j = 2*k-1; break;
   case 3: case 5:  j = 3*k+1; break;
   case 4:  j = 4*k-1; break;
   case 6: case 7: case 8:  j = k-2; break;
}

18.

int i; 
bool foundNonZero;
for (i=0, bool allZeros=false; i < n  && !allZeros;  i++, allZeros=!foundNonZero)               
    for (int j=0, foundNonZero=false;  j< n && !foundNonZero  ;  j++) 
         if (x[i][j] != 0)
               foundNonZero = true;      
cout << "First all-zero row is row " << --i << endl;
       
        

Back to COMS 362 Syllabus Page