Lecture 2 Recursion
Lecture 2 Recursion
Introduction
• Recursion:
0! = 1 (By Definition!)
– Process of solving a problem by n! = n x (n – 1) ! If n > 0
reducing it to smaller versions of itself 3! = 3 x 2!
• Recursive algorithm: 2! = 2 x 1!
Recursion – Algorithm that finds the solution to a
given problem by reducing the problem
1! = 1 x 0!
Definitions Definitions
• Recursive method: • Directly recursive: a method that calls itself
– Method that calls itself • Indirectly recursive: a method that calls another method and eventually results in
• Base case: the original method call. Method A calls method B, which in turn calls method A.
– Case in recursive definition in which the solution is obtained directly
– Stops the recursion
• Infinite recursion:
– Case where every recursive call results in another recursive call.
• General case:
– It is caused by either omitting base case or writing recursion step that does not converge on base
– Case in recursive definition in which a smaller version of itself is called case.
– Must eventually be reduced to a base case – Memory may get exhausted.
1
BBIT 1201 5/22/2023
9 10
2
BBIT 1201 5/22/2023
14
3
BBIT 1201 5/22/2023
Fibonacci of 0 is: 0
Fibonacci of 1 is: 1
Fibonacci of 2 is: 1
Fibonacci of 3 is: 2
Fibonacci of 4 is: 3
Fibonacci of 5 is: 5
Fibonacci of 6 is: 8
Fibonacci of 7 is: 13
21
23 24
4
BBIT 1201 5/22/2023
• Any problem that can be solved recursively can also be solved iteratively
(nonrecursively).
• A recursive approach is normally preferred over an iterative approach when the
recursive approach more naturally mirrors the problem and results in a program that
is easier to understand and debug.
• A recursive approach can often be implemented with fewer lines of code.
• Another reason to choose a recursive approach is that an iterative one might not be
apparent.
25