+ 2
Explain tail recursion
3 odpowiedzi
+ 1
Md Ibrahim (West Bengal, India) I hope you are aware (feel free to ask if not) about function call mechanism & recursion.
tail recursion is the one which don't ask to have further operation / computation from recursive function once call is passed to another function...
for example :
void sayhi(int a)
{
if (a>0) {cout << "Hi" << endl;}
sayhi(a-1);
}
Above function is called tail recursive.why ? because compiler can optimise code and further ignore from where function was called.there is no harm in doing so by compiler to optimise code.
eg. sayhi(3); would print hi for a = 3 , call function sayhi(2) and forget this function at all because it has nothing to perform for sayhi(3) once sayhi(2) is also completed.
above optimise is not possible for non tail recursive.
void print(int a)
{
if (a>0)
{print(a-1);}
cout << a;
}
here ,compiler can't optimise and it has to remember from where recursive call was done..print(3) would call print(2) and has to remember that there is something left to be done for print(3)
+ 3
Ketan Lalcheta
Thanks for your valuable ans. It's helpful.
May I mention you for my future queries?
+ 1
you can... I would get back as and when time permits....