Professional Documents
Culture Documents
Lab 7 Nov 15,16 (2PM), 17
Lab 7 Nov 15,16 (2PM), 17
Lab 7 Nov 15,16 (2PM), 17
[1]https://willrosenbaum.com/teaching/2021s-cosc-112/notes/recursive-image/
Recursion
• Recursion is a method of solving a computational problem
where the solution depends on solutions to smaller instances
of the same problem.
• A programming technique where a function calls itself!
A Function A Recursive Function
Output Output
Main
(Global Namespace/Scope)
Function
(Local Namespace/Scope)
Main
(Global Namespace/Scope)
Main
(Global Namespace/Scope)
sayHello line 1
Function
(Local Namespace/Scope)
Main
(Global Namespace/Scope)
sayHello line 1
Main
(Global Namespace/Scope)
sayHello line 1
Function
(Local Namespace/Scope)
Main
(Global Namespace/Scope)
sayHello line 1
Function
(Local Namespace/Scope)
Main
(Global Namespace/Scope)
sayHello line 1
Function
(Local Namespace/Scope)
Main
(Global Namespace/Scope)
sayHello line 1
Function
(Local Namespace/Scope)
Main
(Global Namespace/Scope)
sayHello line 1
Function
(Local Namespace/Scope)
Main
(Global Namespace/Scope)
sayHello line 1
Function
(Local Namespace/Scope)
Main
(Global Namespace/Scope)
sayHello line 1
Function
(Local Namespace/Scope)
Main
(Global Namespace/Scope)
sayHello line 1
Function
(Local Namespace/Scope)
Main
(Global Namespace/Scope)
sayHello line 1
• In programming, goal is to NOT have infinite recursion
NOT GOOD !
Sum of Integers From 1 to N
sumNumber(6)
sumNumber(6) sumNumber(5)
sumNumber(6) sumNumber(5) sumNumber(4)
sumNumber(6) sumNumber(5) sumNumber(4) sumNumber(3)
sumNumber(6) sumNumber(5) sumNumber(4) sumNumber(3) sumNumber(2)
Recursive Step Base Step
1
sumNumber(6) sumNumber(5) sumNumber(4) sumNumber(3) sumNumber(2) sumNumber(1)
BASE
3
sumNumber(6) sumNumber(5)
21 sumNumber(6)
QUESTION
factorial(5)
return -> 4 * factorial(3)
factorial(5) factorial(4)
return -> 3 * factorial(2)
BASE
return -> 2 * factorial(1)
1
24
factorial(5) factorial(4)
120 factorial(5)
QUESTION
Input : 9 Output : 21
Input : 9 Output : 0 1 1 2 3 5 8 13 21
f(5)
f(3) f(4)
f(1) f(2)
References
• MIT OPENCOURSEWARE- Introduction to Computer Science and
Programming In Python, Fall 2016
• Gökçe Uludoğan- CMPE 150, Fall 2021
• Mehmet Turan – CMPE 150, Fall 2023