Quiz 07 sample questions and answers

The quiz will have two questions, and cover material on recursion.


In the first question, you will demonstrate your ability to read recursive methods. For example, a question might read:

In the following method, (i) identify the implicit and explicit base case(s), (ii) identify the recursive case(s), and (iii) state whether the method will always terminate normally, that is, without throwing an exception. If (i) or (ii) are implicit, then note what they depend upon; or, if (i) or (ii) are missing, then note that fact.

static int fib(int n) {
    if (n == 0) {
        return 1;
    }
    else {
        return fib(n - 1) + fib(n - 2);
    }
}

Assume n > 0 when first invoked.

The base case is when n == 0. Arguably a base case for n == 1 is missing.

The recursive case is when n > 0 (or n > 1, if you argue that n == 1 is a missing base case).

The method will not always terminate normally. For n > 0, it will skip the base case and recurse into negative numbers until it blows the call stack.


In the second question, you will show you can write simple recursive methods given a textual description of their behavior. For example, a question might state:

Write a recursive definition (not the code) for contains on a linked list of Node<E>, starting at a given node, in the style from lecture.

contains(node, e) is:

Then, implement boolean contains(Node<Integer> node, int e) using recursion – no explicit loop constructs (for, while) allowed!

public boolean contains(Node<Integer> node, int e) {
	if (node == null) {
		return false;
	}
	if (node.data == e) {
		return true;
	}
	return contains(node.next, e);
}