|
|
The Department of Computer Science & Engineering
|
CSE 115
Introduction To Computer Science for Majors I
Lecture C
Lecture Notes #27
Stuart C. Shapiro
Spring, 2007
Recursion
Recursion is a kind of loop in which a method calls itself.
To write a recursive method for a problem takes two steps:
- 1. Base Case
- The base case is an instance of the problem that doesn't require recursion.
- 2. Recursive Step
- The recursive step solves the instance of the problem by some
computation based on calling the method itslef with an
instance of the problem that is closer to the base case.
Example: the factorial of n, abbreviated n!, is the product of all
positive integers from 1 to n, or stated recursively, 1! = 1 and n! =
n*(n-1)!
By common definition, 0!=1, and we can define n! to also be 1 if n is negative.
Factorial in Java:
public static int fact(int n) {
if (n<= 0) {return 1;} // Base case
else {return n * fact(n-1);} // Recursive step
To make sure that the recursive method is correct requires three
steps:
- The base case must be correct.
- The recursive call must be of an instance of the problem closer
to the base case.
- The recursive step must be correct assuming that the recursive
call yields the correct answer.
Example: the factorial method defined above:
- The base case is correct, because if n<=0, n!=1 by definition.
- The recursive call is of an instance of the problem closer
to the base case, because if n>0, n-1 is closer to 0 than n is.
- The recursive step is correct assuming that the recursive
call yields the correct answer, because of fact(n-1) =
1*...*(n-1), then n*fact(n) = 1*...*(n-1)*n = 1*...*n.
Copyright © 2007 by Stuart C. Shapiro. All rights
reserved.
Last modified: Fri Dec 7 10:14:03 EST 2007
Stuart C. Shapiro
<shapiro@cse.buffalo.edu>