Self-assessment 07: Sample answers

In the first two questions, 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 factorial(int n) {
    if (n == 0) {
        return 1;
    }
    else {
        return n * factorial(n - 1);
    }
}

Assume n >= 0 when first invoked.


The base case is when n == 0.

The recursive case is when n > 0.

The method will always terminate normally (if the assumption holds).


In the third 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.equals(e)) {
        return true;
    }
    return contains(node.next, e);
}