Académique Documents
Professionnel Documents
Culture Documents
Idea
A few examples
wishful thinking method
Recursion in classes
Ex: palindromes
Helper functions
Computational complexity of recursive functions
Recursive functions with multiple calls
Recursion [Bono]
Announcements
PA2 due Wed.
Lab this week: recursion problems on
codingbat.com (see lab description)
Policy on regrades one week after you get it
back.
For programming assgts:
email has pa score and feedback
check score entered correctly on d2l
for scoring mistakes: you have until this Wed to initiate a
regrade (email grader bottom of feedback email)
Recursion [Bono]
What is recursion?
Recursion [Bono]
Recursion [Bono]
Example: writeStars
// writes n asterisks on a line
public static void writeStars(int n) {
if (n==0) {
System.out.println();
}
else {
System.out.print(*);
writeStars(n-1);
}
}
Recursion [Bono]
Example: exponentiation
How can we compute bn in terms of a smaller
version of the problem?
in other words
If we already know the answer to bn-1,
how can we use that to compute bn?
Recursion [Bono]
Example: exponentiation
A recursive function that returns a value
// compute bn
public static int expon(int b, int n) {
if (n == 0) {
return 1;
else {
return b * expon(b,n-1);
}
|
Recursion [Bono]
Example: printNto1
Print the numbers from n down to 1
Example calls:
printNto1(3);
printNto1(1);
// writes 3 2 1
// writes 1
Recursion [Bono]
Example: print1ToN
Print the numbers from 1 up to n
Example calls:
print1ToN(3);
print1ToN(1);
// writes 1 2 3
// writes 1
Recursion [Bono]
10
Ex: Palindromes
palindromes read the same in both directions, e.g.:
radar
Madam, Im Adam
A man, a plan, a canal. Panama!
radar
deleveled
diefied
racecar
naan
11
recursive isPalindrome
// returns true iff s is a palindrome
// (reads the same forwards and backwards)
public static boolean isPalindrome(String word)
Recursion [Bono]
12
Recursion [Bono]
13
14
15
fib(2)
fib(2)
fib(3)
fib(2)
fib(2)
fib(1)
fib(1)
fib(1)
Recursion [Bono]
16
Recursion [Bono]
17
Recursion [Bono]
18
Summary
Todays examples simple, to understand the
concept:
Loop versions roughly as easy
Same big-O times for both
O(n) space for these recursive versions
19