Recursion is a programming technique in which a function calls itself directly or indirectly. Using a recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.
3. Recursion
The process in which a function calls itself is called recursion. The function calling itself is called
recursive function
Let us assume a programmer has to find sum of first n natural numbers
There are two approaches to find the sum of series
Iterative Algorithm: (using loops for repetitions)
𝑆𝑛 = 1 + 2 + 3 + … + 𝑛
Recursive Algorithm: (using function for
repetitions)
𝑓 𝑛 = 0 𝑛 = 0
𝑓 𝑛 = 𝑛 + 𝑓 𝑛 − 1 𝑛 ≥ 1
4.
5. Example 2:
Find factorial of a number entered by the user.
Iterative Algorithm: (using loops for repetitions)
𝐹𝑛 = 𝑛 𝑛 − 1 𝑛 − 2 𝑛 − 3 … .1
Recursive Algorithm: (using function for
repetitions)
𝑓 𝑛 = 1 𝑛 = 1
𝑓 𝑛 = 𝑛 ∗ 𝑓 𝑛 − 1 𝑛 > 1
9. Tower of Hanoi – Iterative Solution
1. Calculate the total number of moves required i.e. "pow(2, n) - 1" here n is number of disks.
2. If number of disks (i.e. n) is even then interchange destination pole and auxiliary pole.
3. for i = 1 to total number of moves:
if i%3 == 1:
legal movement of top disk between source pole and destination pole
Either there will be minimum flow or least flow btw poles
if i%3 == 2:
legal movement of top disk between source pole and auxiliary pole
Either there will be minimum flow or least flow btw poles
if i%3 == 0:
legal movement of top disk between auxiliary pole and destination pole
Either there will be minimum flow or least flow btw poles