0% found this document useful (0 votes)
20 views2 pages

4 - Tail Recursion

4- Tail Recursion

Uploaded by

specsdeveloper13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views2 pages

4 - Tail Recursion

4- Tail Recursion

Uploaded by

specsdeveloper13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Trending Now Data Structures Algorithms Topic-wise Practice Python Machine Learning Data Science J

Kotlin Tail Recursion


Read Discuss Courses Practice

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.

Benefits of using tail recursion –

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.

Example 1: Find the factorial of a number using tail-recursion.

Kotlin

// Kotlin program of factorial using tail-recursion


fun Fact(num: Int, x:Int):Long{

return if(num==1) // terminate condition


x.toLong()
else
Fact(num-1,x*num) //tail recursion
}
fun main() {
var n = 1
var result = Fact(5,n)
println("Factorial of 5 is: $result")
}

Output:

Factorial of 5 is: 120

Working of the above program-

Example 2:
Find the sum of elements of an array using tail-recursion

Kotlin

// two parameters passed an array and size of array


fun sum(args: Array<Int> , index:Int, s : Int = 0 ):Int{
return if(index<=0) s
else sum(args ,index-1, s + args[index-1]) // tail-recursion
}

You might also like