Direct Vs. Indirect Recursion
This lesson explains two different types of recursion: direct and indirect recursion.
Direct Recursion
Direct recursion occurs when a function calls itself.
This results in a one-step recursive call: the function makes a recursive call inside its own function body.
Syntax of Direct Recursion
def function1(p1, p2, ..., pn) :
# Some code here
function1(p1, p2, ..., pn)
# Some code here
Printing Natural Numbers from to Using Direct Recursion
Let’s have a look at an example that prints natural numbers from to :
def printNaturalNumbers(lowerRange, upperRange):# Base Caseif lowerRange > upperRange :returnprint(lowerRange)# Recursive CaseprintNaturalNumbers(lowerRange + 1, upperRange);# Driver Coden = 5printNaturalNumbers(1, n)
In the above code snippet, if lowerRange
is less than upperRange
, we print the lowerRange
, increase it and call the function again. But if lowerRange
is greater than upperRange
, we halt function calls.
The slides below show how function calls are being performed and then how all the functions return.
Indirect Recursion
Indirect recursion (or mutual recursion) occurs when a function calls another function, eventually resulting in the original function being called again.
For example, if function function1()
calls another function function2()
and function2()
eventually calls the original function function1()
- this phenomenon results in indirect recursion (or mutual recursion).
Syntax of Indirect Recursion
def function1(p1, p2, ..., pn) :
# Some code here
function2(p1, p2, ..., pn)
# Some code here
def function2(p1, p2, ..., pn) :
# Some code here
function1(p1, p2, ..., pn)
# Some code here
Printing Natural Numbers from to Using Indirect Method
Let’s have a look at an example that prints natural numbers from to :
def printNaturalNumbers(lowerRange, upperRange) :if lowerRange <= upperRange :print(lowerRange)lowerRange += 1helperFunction(lowerRange, upperRange)else :returndef helperFunction(lowerRange, upperRange) :if lowerRange <= upperRange :print(lowerRange)lowerRange += 1printNaturalNumbers(lowerRange, upperRange)else :return# Driver Programn = 5printNaturalNumbers(1, n)
In this code snippet, we have two functions: printNaturalNumbers()
and helperFunction()
. Both of them check if lowerRange
is greater than upperRange
. If not, then print lowerRange
and call the other function.
This may not look like recursion, because a function is not calling itself. However, if we analyze the code flow, the first function always ends up calling itself indirectly.
Have a look at the code flow:
Now that you have understood the concept of direct and indirect recursion, let’s move on and find out when we should use recursion in the next lesson.