Introduction to
Recursion
Lecture 20
Administrative Issues
•
Due Today
– Homework 4
• Ongoing
– Program 4
•
Due Friday, June 20
th
at 11pm
Method Calls
•
Many examples of calling a method to
perform a service
–
println()
–
shuffle()
–
addPhoneBookEntry()
–
unplug()
•
Called one method from inside another
Review: The Stack Trace
main()
method1()
helpMethod()
Class 1
Class 2
obj.method1()
helpMethod
()
Recursive Method Calls
•
Methods can also call themselves
•
This is called
recursion
– Very powerful tool
– Easytoimplement and elegant solutions to
some problems
Recursion
•
Defining something in terms of itself
•
Bad practice for a dictionary
–
Writer: A person that writes
–
Write: The action performed by a writer
•
However, can be useful to define certain concepts
–
list
:
number
or
number, list
•
5, 6, 7, 4, 3, 6, 22
• 6
•
76, 22, 32, 3
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
The Base Case
•
Recursive definitions must have terminating
condition, or
base case
– If not, they never end!
• Example
–
list
:
number
or
number, list
•
Without the base case, lists would all be
infinitely long
– Similar to an infinite loop
Two Parts
•
Two parts of a recursive definition
– The base case
– The recursive step
•
Both parts are required
Recursion in Math
•
Recursion can define many mathematical
concepts
• Factorial
1! = 1
n! = n·(n–1)!
•
Powers of two
2
0
= 1
2
n
= 2·2
n–1
Thinking Recursively
•
Clichés often think recursively
– “Take it one problem at a time.”
– “We play the season one game at a time.”
•
Think: “If I can solve this smaller problem
first…”
•
Example: Factorial of 50!
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '01
 Kim
 Space, Recursion, base case, Hanoi

Click to edit the document details