This preview shows pages 1–2. Sign up to view the full content.
1
CS100J
February 20
Recursion
Recursion
: If you get the point, stop;
otherwise, see Recursion.
Infinite recursion
: See Infinite recursion.
Read: pp. 403408 but SKIP sect. 15.1.2
Look in ProgramLive CD, page 153, for
some interesting recursive methods.
Download presented algorithms from
the website
Recursive deﬁnition
: A deﬁnition that is deﬁned in
terms of itself.
Recursive method
: a
method
that calls itself
(directly or indirectly).
Recursion is often a good alternative to iteration
(loops), which we cover next. Recursion is an
important programming tool. Functional languages
have no loops —only recursion.
2
Turn recursive deﬁnition into recursive function
Factorial
:
!0 = 1
base case
!n = n * !(n1)
for n > 0
recursive case
Thus, !3 = 3 * !2
= 3 * 2 * !1
= 3 * 2 * 1 * !0
= 3 * 2 * 1 * 1
(= 6)
// = !n
(for n
≥
0)
public static int
fact(
int
n) {
if
(n == 0) {
return
1;
base case
}
// {n > 0}
an assertion
return
n * fact(n1);
recursive case
}
(a recursive call)
note the precise speciﬁcation
3
Two issues in
coming to grips with recursion
1. How are recursive calls executed?
2. How do we understand a recursive
method and how do we create one?
We discuss the ﬁrst issue later. Sufﬁce it to say
that if you execute a call on a recursive
method, carefully using our model of
execution, you will see that it works. Brieﬂy, a
new frame is created for each recursive call.
DON’T try to
understand
a recursive
method by executing its recursive calls!
Use
execution only to understand how it works.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview. Sign up
to
access the rest of the document.
 Spring '07
 DAVIDGRIES
 Algorithms, Recursion

Click to edit the document details