2. WHAT IS RECURSION??
• The process in which a function calls itself directly or
indirectly is called recursion and the corresponding
function is called as recursive function.
5. TAIL RECURSION:
If a recursive function is calling itself and that recursive call is the
last statement of the recursive function, then it is called as tail
recursion.
After the calling of the last statement there is nothing to execute in
the recursive function.
6. EXAMPLE OF TAIL RECURSION:
Void fun(int n)
{
if(n>0)
{
Printf(“%d”,n);
fun(n-1);
}
}
>>>fun(3)
Result produced: 3,2,1
Last Statement of the recursive function
7. TAIL RECURSION OR NOT..
• Void fun(int n)
• {
if(n>0)
{
//Some code
fun(n-1)+n;
}
• }
All these operation perform in calling time only. The function not
be performing any operation in returning time
unless result of the function is known addition
operation is not performed.
In this case function has to perform operation on
returning time , so this is not a tail recursion.
It is also the last statement of the recursive function
8. TAIL RECURSION VS. LOOP:
Void fun(int n)
{
while(n>0)
{
Printf(“%d”,n);
n--;
}
}
Passing value:fun(3)
Every recursive function can be written
as loop and vise versa.
9. COMPARISON :
● Time complexity: O(n) O(n)
● Space complexity: O(1) O(n)
LOOP Tail recursion
10. Tail Recursive VS. Non-Tail Recursive
1.The tail recursive functions considered better than non tail recursive
functions as tail-recursion can be optimized by compiler.
2.The idea used by compilers to optimize tail-recursive functions is
simple, since the recursive call is the last statement, there is nothing
left to do in the current function, so saving the current function’s stack
frame is of no use
11. CONCLUSION:
● It is better to convert tail recursion into loop for better
efficiency in terms of space.
● This is not true for all recursion or loop.
● It is efficient only in tail recursion.