Javatpoint Logo
Javatpoint Logo

Kotlin Recursion Function

Recursion function is a function which calls itself continuously. This technique is called recursion.

Syntax

Kotlin recursion function example 1: Finite times

Let's see an example of recursion function printing count.

Output:

hello 1
hello 2
hello 3
hello 4
hello 5

Kotlin recursion function example 2: Factorial Number

Let's see an example of recursion function calculating factorial of number.

Output:

Factorial of 5 = 120

Working process of above factorial example

Kotlin Tail Recursion

Before we will discuss about the tail recursion, let's try to make an example which calculate sum of nth (100000 larger number) using general (normal) recursion.

General Recursion

Let's see an example of calculating sum of nth (100000 larger number) using general (normal) recursion.

Output:

Exception in thread "main" java.lang.StackOverflowError

The above example throws an exception of "java.lang.StackOverflowError". This is because the compiler is unable to call large number of recursive function call.

Tail Recursion

Tail recursion is a recursion which performs the calculation first, then makes the recursive call. The result of current step is passed into the next recursive call.

Tail recursion follows one rule for implementation. This rule is as follow:

The recursive call must be the last call of the method. To declare a recursion as tail recursion we need to use tailrec modifier before the recursive function.

Kotlin Tail Recursion Example 1: calculating sun of nth(100000) number

Let's see an example of calculating sum of nth (100000 larger number) using tail recursion.

Output:

sun of upto 100000 number = 5000050000

Kotlin Tail Recursion Example 2: calculating factorial of number

Let's see an example of calculating factorial of number using tail recursion.

Output:

Factorial of 4 = 24





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA