Professor Abdul-Quader
Recursion
Last lesson:
A method which invokes itself is called recursive. The add
method invokes itself (as long as \(y \neq 0\)).
Recursive methods have a base case: a condition which leads to an actual answer, rather than recursively calling the same method again.
add
method?add(x, y)
, how “deep” does the recursion go?5 minutes to discuss these at your tables. Nominate one person from your room to share.
Project design:
public int recursiveFactorial(int n) {
if (n <= 0) {
return 1;
}
return n * recursiveFactorial(n - 1);
}
recursiveFactorial(n-1)
correctly returns \((n-1)!\).recursiveFactorial(n-1)
is, in fact, equal to \(n!\) (Why?)Implement a recursive Fibonacci method. Remember:
fib(0)
should return \(0\)fib(1)
should return \(1\)fib(n)
should return fib(n-1) + fib(n-2)
if \(n > 1\).public static void printBeforeRecursion(ArrayList<String> list, int i) {
if (i == list.size()) {
return;
}
System.out.println(list.get(i));
printBeforeRecursion(list, i+1);
}
public static void printAfterRecursion(ArrayList<String> list, int i) {
if (i == list.size()) {
return;
}
printAfterRecursion(list, i+1);
System.out.println(list.get(i));
}
(If time): Problem: Given a (positive) integer, add up its digits.
Recursive idea:
Starter code Implement the sumDigits method recursively. Hint: to get the ones digit of a number, use \(num % 10\). To remove the ones digit from the number, use \(num / 10\).