Recursion Types and Limit
Learn about the usage of different types of recursion.
We'll cover the following...
Types of recursion
There are two types of recursions:
- Head recursion
- Tail recursion
Head recursion
In this type of recursion, the recursive call is made before other processing in the function, as shown below:
Press + to interact
def headprint(n) :if n == 0 :returnelse :headprint(n - 1)print(n)headprint(10)
In the code above, the recursive call happens first, and then the printing takes place. Therefore, the last value of n
, i.e., 1, is printed first. So numbers are printed in the order 1 to 10.
Tail recursion
In this type of recursion, the processing is done before the recursive call. The tail recursion is similar to a loop—the function executes all the statements before making the recursive call.
Press + to interact
def tailprint(n) :if n == 11 :returnelse :print(n)tailprint(n + 1)tailprint(1)
In the code above, printing takes place first, and ...