Answers to Self-Study Questions

Test Yourself #1

The printInt method does obey recursion rule 1; it does have a base case, namely:

It obeys recursion rule 2 in a sense; the code: makes progress toward the base case as long as k is greater than zero. However, all calls with actual parameters less than zero will cause an infinite recursion. Assuming that the intention is to print only positive values, this could be fixed by changing the base case to:

Test Yourself #2

The call printTwoInts(3) causes teh following to be printed:

Test Yourself #3

Question 1: The call factorial(3) leads to three recursive calls; when all calls are still active, the runtime stack would be as shown below (showing just the values of parameter N). The values returnedby each call are also shown.

Question 2: The iterative version of factorial will return -1 as the result of the call factorial(-1). The recursive version will go into an infinite recursion (because the base case, N==0, will enver be reached).

Since, mathematically, factorial is undefined for negative numbers, a call to factorial with a negative number should cause an exception. This is easily done for the iterative version:

(where NegativeValueException would have to be defined as a public exception).

For the recursive version, we could change the method to:

However, the problem with this is that the check for N < 0 will be made on every call, including the recursive calls where it cannot be true. This makes the method slightly less efficient. A better solution would be to make the check once, the first time factorial is called, and then use an auxiliary, recusive method with no check: