Professional Documents
Culture Documents
Programming II
Faculty of
Computer Science
Faculty of Computer Science
Index
• What is recursion?
• Exercises
Recursion 2
What is recursion?
Programming II
Faculty of
Computer Science
Faculty of Computer Science
Recursion 4
Faculty of Computer Science
Recursion 5
Faculty of Computer Science
Recursion 6
Faculty of Computer Science
Recursion 7
Faculty of Computer Science
Recursion 8
Faculty of Computer Science
As a summary…
Recursion 9
How recursion works
Programming II
Faculty of
Computer Science
Faculty of Computer Science
Recursion 11
Faculty of Computer Science
Recursion 12
Faculty of Computer Science
Factorial(3)
Stack status
Result ?
n 3 First call
Return address R1
Activation
Memory
record (Stack)
Recursion 13
Faculty of Computer Science
Factorial(3) = 3*Factorial(2)
Stack status
Result ?
n 2 Second call
Return address R2
?
3 First call
R1
Memory
Recursion 14
Faculty of Computer Science
Factorial(2) = 2*Factorial(1)
Result ?
Stack status
n 1 Third call
Return address R2
?
2 Second call
R2
?
3 First call
R1
Memory
Recursion 15
Faculty of Computer Science
Factorial(1) = 1*Factorial(0)
Result 1
n 0 Fourth call
Return address R2
?
Stack status
1 Third call
R2
?
2 Second call
R2
?
3 First call
R1
Memory
Recursion 16
Faculty of Computer Science
Return
Result 1
Stack status
n 1 Third call
Return address R2
?
2 Second call
R2
?
3 First call
R1
Memory
Recursion 17
Faculty of Computer Science
Return
Stack status
Result 1
n 2 Second call
Return address R2
?
3 First call
R1
Memory
Recursion 18
Faculty of Computer Science
Return
Stack status
Result 2
n 3 First call
Return address R1
Memory
Recursion 19
Faculty of Computer Science
End
Result 2
n 3
Return address R1 Result = 6
Memory
Recursion 20
Faculty of Computer Science
time
Recursion 21
Faculty of Computer Science
To begin with …
Recursion 22
Faculty of Computer Science
To begin with …
Recursion 23
Developing recursive
programs:
the induction method
Programming II
Recursion 25
Faculty of Computer Science
1. Induction basis: Identify base cases (i.e. trivial cases with direct
solution):
n=1 meets 101-1 = 10-1 = 9 = 9*1
2. Establish the induction hypothesis: Assume that the property is
fulfilled for a case simpler than the general one (n):
assume that n-1 meets 10(n-1)-1 = 9*a
3. Induction step: Using the hypothesis, we prove the general case:
since 10(n-1)-1 = 9*a we can prove that it is true for all n:
10n-1 = 10*10(n-1)-(10-9) = 10*10(n-1)-(10-9) = (10*10(n-1)-10)+9 =
= 10*(10(n-1)-1)+9 = 10*(9*a)+9 = 9*(10*a+1) = 9*b
Recursion 26
Faculty of Computer Science
Recursion 27
Faculty of Computer Science
Recursion 28
Faculty of Computer Science
Recursion 29
Faculty of Computer Science
Return
Parameter n Stop instruction
value
3 5 Factorial = 3 *Factorial(2); 6
2 5 Factorial = 2 *Factorial(1); 2
1 5 Factorial = 1 *Factorial(0); 1
0 -- 1
Recursion 30
Faculty of Computer Science
Recursive or Iterative?
Recursion 31
Recursion: Exercises
Programming II