In this reading/viewing we will have a look at a programming technique known as recursion. At its simplest, recursion is just when a method calls itself. However, at its heart recursion is a powerful problem solving strategy that involves decomposing a problem into smaller versions of the same problem.
To start we’ll look at the essential components of a recursive algorithm/method and see a couple of classic examples involving recursion. Recursion will seem a bit mystical at first; with repeated application it will become another wonderful tool in our programming toolbox.
Each student will be responsible for learning and demonstrating proficiency in the following objectives PRIOR to the class meeting. The reading quiz will test these objectives.
long
and int
types in Java.The following objectives should be mastered by each student DURING and FOLLOWING the class session through active work and practice.
These exercises are geared towards mastering the BASIC learning objectives listed above. You are expected to submit them before class and it is highly recommended that you complete them before attempting the reading quiz.
In your own words, describe why a base case is required in an recursive method.
Consider the following recursive method:
public static int foo(int x)
{
if (x == 1)
return 1;
else {
return foo(x-1) + 1;
}
}
Part A: What is the base case(s)?
Part B: What is the recursive case(s)?
Part C: Assuming that we call foo(10)
from a main
method, what is the most number of items on the call stack when executing the code? Hint: Review section 12.3.2 for a refresher on the call stack.