![]() |
VOOZH | about |
In this tutorial, we will learn about Kotlin Recursive functions. 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:
Table of Content
When a function is called from main() block then it is called a normal function call. In below example, sum() is called at a time and it executes its instruction and terminate with returning the sum of number. If we want to execute the function again then we should call sum() from the main block one more time.
Calling sum() function from main() block
👁 ImageWhen a function calls itself then it is called recursive function call. Every recursive function should have terminate condition else program executions enters in infinite loop and results into stack overflow error.
Calling the callMe() function from its block
👁 ImageHere, 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.
Example 1: Find the factorial of a number without using the terminating condition
Output:
Exception in thread "main" java.lang.StackOverflowErrorExample 2: Find the factorial of a number using a terminating condition
Output:
Factorial of 5 is: 120The recursive call of Fact() is explained step by step in the following figure👁 Image
Example 3: Find the sum of elements of an array using recursion
Output:
The sum of array elements is: 55Explanation: Here, we have initialized an array and passed as an argument to the sum() function. In each recursive call the index value decrement by one. If the index equal to zero or less than then terminate it and return the sum of all the elements.