![]() |
VOOZH | about |
In a 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 give the same output. The must-follow rule for tail recursion is that the recursive call should be the last call of the method.
Example 1: Find the factorial of a number using tail recursion
Output:
Factorial of 5 is: 120Working of the above program👁 Image
Example 2: Find the sum of elements of an array using tail-recursion
Output:
The sum of array elements is: 55Explanation: Here, we have passed the array as an argument along with two other parameters to the sum() function. The default value of the (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 the condition is satisfied.