BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Kotlin Recursion and Tail Recursion with examples

By Chaitanya Singh | Filed Under: Kotlin Tutorial

A function is called recursive function if it calls itself and this process is called recursion.

How a recursive function looks like?

Here the function myfunction() calls itself, this is a recursive function.

fun myfunction(){    
  //some code  
  ....
  //myfunction() calling myfunction()
  myfunction()   
}

Lets take an example to understand the recursion.

Kotlin Recursion example

This is a simple example of factorial. Here we have defined a function fact() to calculate the factorial of a number that it passed to this function as a parameter. In the function body we are calling this function again, this process is called recursion.

User is asked to enter a positive integer number and based on the input, program finds the factorial of the input number by passing the input number as an argument to the user defined function fact().

fun main(args: Array<String>) {
    print("Enter a positive integer number: ")
    val number: Int =Integer.valueOf(readLine())
    val factorial = fact(number)
    println("Factorial of $number = $factorial")
}

//recursive function
fun fact(num: Int): Int {
    return if(num == 1){
        num
    }
    else{
        //function fact() calling itself
        num*fact(num-1)
    }
}

Output:
Kotlin Recursion example

Tail Recursion

In recursion the computation is done after the recursive call, the example of factorial we have seen above is an example of recursion or head recursion where to calculate the factorial of n we need the factorial of n-1.

In Tail recursion the computation is done at the beginning before the recursive call. In tail recursion the call to the recursive function occurs at the end of the function. Which means the computation is done first and then passed to the next recursive call.

Lets take an example of tail recursion.

Tail Recursion Example

To declare a tail recursive function we use tailrec modifier before the function.

fun main(args: Array<String>) {
    val number = 6
    val factorial = fact(number)
    println("Factorial of $number = $factorial")
}

tailrec fun fact(n: Int, temp: Int = 1): Int {
    return if (n == 1){
        temp
    } else {
        fact(n-1, temp*n)
    }
}

Output:
Tail Recursion

❮ PreviousNext ❯

Comments

  1. JP says

    December 11, 2019 at 3:03 AM

    This tail recursive example works the same even without the “tailrec” modifier

    Reply
    • Joyson John says

      September 22, 2020 at 7:00 AM

      Since it is a small value, ‘6’ it will work without “tailrec”. But if you use bigger value such as 10000, it needs “tailrec” to avoid ‘stackover flow’ error.

      Reply
  2. Mikhail Ismail says

    January 17, 2021 at 12:57 PM

    The kotlin recursion doesn’t print out any results on my compiler

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Kotlin Tutorial

  • Kotlin Tutorial
  • Kotlin in Eclipse IDE
  • Kotlin in IntelliJ
  • First Kotlin Program
  • Kotlin Keywords
  • Kotlin Variables
  • Kotlin Type Casting
  • Kotlin operators
  • Kotlin Input/Output
  • Kotlin Comments

Kotlin String

  • Kotlin String

Kotlin Array

  • Kotlin Array
  • Kotlin Range

Control Flow

  • Kotlin if expression
  • Kotlin when expression
  • Kotlin for loop
  • Kotlin while loop
  • Kotlin do-while loop
  • Kotlin continue
  • Kotlin break

Kotlin Function

  • Kotlin Function
  • Kotlin Recursion
  • Kotlin default and named arguments
  • Lambda functions
  • Higher Order Function

Exception Handling

  • Exception Handling
  • Kotlin try catch
  • Multiple catch blocks
  • Nested try catch
  • Throw keyword
  • Kotlin try expression

Kotlin OOP

  • Class and Objects
  • Kotlin Constructors
  • Kotlin Inheritance
  • Visibility Modifiers
  • Kotlin abstract class
  • Kotlin Interfaces
  • Nested and Inner Class
  • Kotlin Data Class
  • Kotlin Sealed Class

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap