CSC2302_Lecture9
CSC2302_Lecture9
Data Structures
Lecture 9: Recursion
Raifa Akkaoui
School of Science and Engineering, AUI
[email protected]
Spring 2024
What’s Recursion?
• One way to describe repetition within a computer program is the use of loops, such as C while-loop and
for-loop
• An entirely different way to achieve repetition; through a process called recursion
• Definition: a technique by which a function makes one or more calls to itself during execution, or
by which a data structure relies upon smaller instances of the very same type of structure in its
representation
• N.B. recursion provides an elegant and powerful alternative for performing repetitive tasks
• Problems that lend themselves to a recursive solution have the following characteristics:
• One or more simple cases of the problem have a straightforward, non-recursive solution
• The other cases can be redefined in terms of problems that are closer to the simple cases
• By applying this redefinition process (i.e., second characteristic) every time the recursive function is
called, eventually the problem is reduced entirely to simple cases, which are relatively easy to
solve
Size 1
Problem
• Factorial function
• n! = 1*2*3*…*(n-1)*n
• if n == 0, n! = 1
• Factorial
1 𝑖𝑓 𝑛 = 0
• n! = ቊ
𝑛 ∗ 𝑛 − 1 ∗ 𝑛 − 2 … ∗ 3 ∗ 2 ∗ 1, 𝑖𝑓 𝑛 ≥ 1
• Recursive definition:
• There is a natural recursive definition for the factorial function
• Observe that, for instance 5! = 5 * (4 * 3 * 2 * 1) = 5 * 4!
• More generally, for a positive integer n, we can define n! to be n * (n−1)!
• This recursive definition can be formalized as:
1, 𝑖𝑓 𝑛 = 0
𝑓 𝑛 =ቊ
𝑛 ∗ 𝑓(𝑛 − 1), 𝑒𝑙𝑠𝑒
• Base Case(s)
• Values of the input variables for which we perform no recursive calls
• There should be at least one base case
• Every possible chain of recursive calls must eventually reach a base case
• e.g., n=0 is our base case in factorial
• Recursive calls
• Calls to the current method
• Each recursive call should be defined so that it progresses towards a base case
Recursion Trace
Stack frame of program while computing 4!