12.1-12.3 Quiz
SR 12.5 Write a recursive definition of 5 * n (integer multiplication), where n > 0. Define the multiplication process in terms of integer addition. For example, 5 * 7 is equal to 5 added to itself 7 times.
5 * n = 5 if n = 1 5 * n = 5 + (5 * (n - 1)) if n > 1
SR 12.4 When is a base case needed for recursive processing?
A base case is always required to terminate recursion and begin the process of returning through the calling hierarchy. Without the base case, infinite recursion results.
SR 12.7 When should recursion be avoided?
Avoid recursion when the iterative solution is simpler and more easily understood and programmed. Recursion has the overhead of multiple method calls and is not always intuitive.
SR 12.8 Describe what is returned by the following recursive method. public int exercise(int n) { if (n < 0) return -1; else if (n < 10) return 1; else return 1 + exercise(n/10); }
If n < 0 a -1 is returned; otherwise the number of digits in the integer n is returned.
SR 12.10 What is indirect recursion?
Indirect recursion occurs when a method calls another method, which calls another method, and so on until one of the called methods invokes the original. Indirect recursion is usually more difficult to trace than direct recursion, in which a method calls itself.
SR 12.3 What is infinite recursion?
Infinite recursion occurs when there is no base case that serves as a terminating condition or when the base case is improperly specified. The recursive path is followed forever. In a recursive program, infinite recursion will often result in an error that indicates that available memory has been exhausted.
SR 12.1 What is recursion?
Recursion is a programming technique in which a method calls itself, solving a smaller version of the problem each time, until the terminating condition is reached.
SR 12.6 Is recursion necessary?
Recursion is not necessary. Every recursive algorithm can be written in an iterative manner. However, some problem solutions are much more elegant and straightforward when written recursively.
SR 12.2 How many times is the recursive part of the definition of a List used to define a list of 10 numbers? How many times is the base case used?
The recursive part of the definition of a List is used 9 times to define a list of 10 numbers. The base case is used once.
Write a recursive method that returns the value of 5 * n, where n > 0. Explain why you would not normally use recursion to solve this problem.
The recursive solution below is more complicated than the iterative version, so it normally would not be done in this way.