In this tutorial, we will learn about kotlin recursive function. We will learn about how a function calls itself. How should you use recursion in kotlin program etc.
Like other programming language, function in kotlin that calls itself is called kotlin recursive function. This technique is called recursion.
Example –
fun main(args: Array<String>) { printHello(); } fun printHello() { println("Hello") printHello(); }
In above program, there are two types function call
– Normal function call
– recursive function call.
Function call of printHello() from main() function is normal function call. Function call of printHello() inside printHello() is recursive function call because printHello() function is calling itself. Notice that the function call inside printHello() function will result in StackOverFlow error because printHello() function keeps calling itself until stack overflow. There is no condition to terminate function call. Hence, it will result in error.
Let’s see another example,
fun main(args: Array<String>) { val product = findSum(5); print("Sum = $product") } fun findSum(num: Int): Int { return if (num == 1) num else num + findSum(num - 1) }
Output –
Sum = 15
The function findSum() calculates sum of n natural number using recursion. The total steps included in the function calls are –
findSum(5) // 1st call to the function with argument 5 5 + findSum(4) // 2nd call to the function with argument 4 5 + (4 + findSum(3)) // 3rd call to the function with argument 3 5 + (4 + (3 + findSum(2))) // 4th call to the function with argument 2 5 + (4 + (3 + (2 + findSum(1)))) // 5th call to the function with argument 1 5 + (4 + (3 + (2 + 1))) // calculations are done in 5th function call.. 5 + (4 + (3 + 3)) // Back to 4th function call, calculations are done 5 + (4 + 6) // Back to 3rd function call, calculations are done 5 + 10 // Back to 2nd function call, calculations are done 15 // Back to 1st function call, calculations are done and result is returned
Notice that functions are being called first. Then, calculations are being done in last step.
Compiler maintains each function call using stack. So, calling function in this way consumes more space. Your program may even throw stackoverflow error if functions are being called too many times.
To overcome such scenario we use tail recursion in function.
Exercises on Kotlin Recursive Function
1. Guess the output of below program
fun main(args: Array<String>) { val product = findProduct(15); print("Sum = $product") } fun findProduct(num: Int): Int { return if (num == 1) num else num * findProduct(num / 2) }
2. Guess the output of below program
fun main(args: Array<String>) { val product = findDiff(5); print("Sum = $product") } fun findDiff(num: Int): Int { return if (num == 1) num else num - findDiff(num - 1) }
That’s end of tutorial on Kotlin Recursive function.
You must be logged in to post a comment.