COM1201 Spring 1997 Professor Fell QUIZ 4 Solution

1. (5 points) Show a NEAT drawing of the resulting list when D(list) is executed and explain briefly what the function D does.



Node* & D(Node* &  list){
	if (list){  
		Node * p;
		p = new Node;
		p->data = list>data;
		p->next = D(list->next);
		list->next = p;
	}
	return list;  
}
list

D makes a copy of each element in the list and inserts it after the original.

2. (5 points) Show the output when a call is made to H(4).

void H(int N){
	cout << N << endl;
	if (N > 1) {
		H(N-1);
		H(N-2);
	} 
}

output  nesting
4   	H(4)
3  	   H(3)
2  	     H(2)
1  	       H(1)
0  	       H(0)
1  	     H(1)
2  	   H(2)
1  	     H(1)
0  	     H(0)
3. (5 points) Given the function K() below, show the output caused by the following calls:
cout << "K(4) = " << K(4) << endl;
cout << endl;
cout << "K(3) = " << K(3) << endl;

int K(int N){
	static int count = 1;
	cout << setw(8) << count++ << setw(8) << N << endl;
	if (N == 0) return 1;
	if (N == 1) return 1;
	return K(N-1) + K(N/2);
}
output     	nesting
1       4      K(4) returns 5
2       2         K(2) returns 2
3       1          	K(1) returns 1
4       1          	K(1) returns 1
5       3         K(3) returns 3
6       1          	K(1) returns 1
7       2          	K(2) returns 2
8       1           		K(1) returns 1
9       1           		K(1) returns 1
K(4) = 5

10 3 K(3) returns 3 11 1 K(1) returns 1 12 2 K(2) returns 2 13 1 K(1) returns 1 14 1 K(1) returns 1 K(3) = 3

4. (5 points) Write a recursive function:

int Q(int A[], int size)

that returns the maximum value among: A[0], A[1], . . . , A[size-1].
int Q(int A[], int size){
// size > 0
	if (size == 1) return A[0];
	int x = Q(A, size-1);
	if (x > A[0]) return x;
	return A[size - 1];
}

Last Updated: April 27, 1997 10:15 pm by

Harriet Fell
College of Computer Science, Northeastern University
360 Huntington Avenue #161CN,
Boston, MA 02115
Internet: fell@ccs.neu.edu
Phone: (617) 373-2198 / Fax: (617) 373-5121
The URL for this document is: http://www.ccs.neu.edu/home/fell/COM1101/QUIZ/Q4/quiz4Solution.html