4 - Tail Recursion
4 - Tail Recursion
In traditional recursion call, we perform our recursive call first, and then we
take the return value of the recursive call and calculate the result. But in tail
recursion, we perform the calculation first, and then we execute the recursive
call, passing the results of the current step to the next recursive call. In the
end, both recursion and tail recursion gives same output. The must follow rule
for the tail recursion is that recursive call should be the last call of the method.
1. In tail recursion, function call is the last thing executed by the function and
nothing left in the current function to execute. So, there is no need to save
current function call in stack memory and compiler can re-use that stack
space for next recursive call.
2. In tail recursion, we do not get the StackOverflowError during the
execution of program.
Kotlin
Output:
Example 2:
Find the sum of elements of an array using tail-recursion
Kotlin