In traditional recursion call, we perform our recursive call first, and then we take the return value of the recursive call and calculate the result. But in tail recursion, we perform the calculation first, and then we execute the recursive call, passing the results of the current step to the next recursive call. In the end, both recursion and tail recursion gives same output.
The must follow rule for the tail recursion is that recursive call should be the last call of the method.
Benefits of using tail recursion –
- In tail recursion, function call is the last thing executed by the function and nothing left in the current function to execute. So, there is no need to save current function call in stack memory and compiler can re-use that stack space for next recursive call.
- In tail recursion, we do not get the
StackOverflowErrorduring the execution of program.
Example 1: Find the factorial of a number using tail-recursion.
Factorial of 5 is: 120
Working of the above program-
Example 2: Find the sum of elements of an array using tail-recursion
The sum of array elements is: 55
Here, we have passed the array as an argument along with two other parameters in
sum() function. The default value of (s) parameter is equal to zero. We are calculating the sum of elements, from the last index of the array, with each recursive call. With the last recursive call, we will have the sum of all elements in s and return it when condition satisfies.
- Kotlin Data Types
- Hello World program in Kotlin
- Kotlin | Retrieve Collection Parts
- Destructuring Declarations in Kotlin
- DatePicker in Kotlin
- Kotlin labeled continue
- Introduction to Kotlin
- Kotlin Type Conversion
- Kotlin Exception Handling | try, catch, throw and finally
- Kotlin if-else expression
- Kotlin Environment setup for Command Line
- Kotlin constructor
- Kotlin Environment setup with Intellij IDEA
- Kotlin Nested class and Inner class
- Kotlin Variables
- Kotlin Operators
- Kotlin Standard Input/Output
- Kotlin Expression, Statement and Block
- Kotlin when expression
- Kotlin for loop
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.