3- Recursion
3- Recursion
Kotlin Recursion
Read Discuss Courses Practice
In this tutorial, we will learn Kotlin Recursive function. Like other programming
languages, we can use recursion in Kotlin. A function that calls itself is called a
recursive function and this process of repetition is called recursion. Whenever
a function is called then there are two possibilities:
Here, we have used the terminate condition if( a > 0) else it enters the infinite
loop. And it prints the value from 5 down to 0.
Java
Output:
Java
Output:
Example 3:
Find the sum of elements of an array using recursion
Java
fun main()
{
// array initialization
val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
// size of array
val n
= array.size val result
= sum(array, n) // normal function call
println("The sum of array elements is: $result")
}
Output:
The sum of array elements is: 55
1. Increased memory usage: Each recursive call adds a new function call to the
call stack, which can lead to stack overflow errors for large data sets.
2. Performance: Recursive algorithms are often slower than iterative
algorithms, as they require more memory and CPU cycles.
Similar Reads
Kotlin Tail Recursion Android - Create Group
BarChart with Kotlin