Kotlin Recursion Functions & Tail Recursion

In this article, you will learn how to create recursion functions in kotlin programming language and also learn tail recursion. Recursion functions means it calls itself continuously.

This kind of process is called as recursion. In normal recursion, we perform all recursive calls first then we calculate result from values. But in tail recursion, first calculations are performed then calls are executed.

 

Recursion Functions

Recursion Process enables the function to repeat several times and give the output. Recursion is useful in programming when task can be split into small same kind of tasks. Recursion makes programming easier for this type of situations. Here the functionName is called itself, so we can call it as recursion functions.
 
fun main(args: Array<String>) {
     functionName()
}

fun functionName() {
     functionName()
}

 


For example: Calculate factorial of number using recursion function

fun main(args: Array<string>) {
     val num = 5
     val answer: Long
     answer = calFact(num)
     println(“Factorial of $num = $answer“)
}

fun calFact(n: Int): Long {
     return if (n == 1) n.toLong() else n*calFact(n-1)
}

 

Process of above example:
factorial(5)
5*factorial(4)
5*(4*factorial(3))
5*(4*(3*factorial(2)))
5*(4*(3*(2*factorial(1))))

Output:
120
 

Tail Recursion

To perform tail recursion in kotlin, we need to give tailrec modifier to the function so compiler can identify. In this process in the function last statement is a recursive call which is executed by same function.

I already explained in this method first we perform calculations then recursive calls are executed. We already calculated factorial of number using recursion. But here we calculate with tail recursion instead of normal recursion.

 

For example: Calculate factorial of number using tail recursion function

fun main(args: Array<string>) {
     val num = 5
     val answer: Long
     answer = calFact(num)
     println(“Factorial of $num = $answer”)
}

tailrec fun calFact(n: Int, m: Int = 1): Long {
     return if (n == 1){
         m.toLong()
     } else {
         calFact(n-1, m*n)
     }
}

One thought on “Kotlin Recursion Functions & Tail Recursion

Leave a Reply