What is Tail Recursion

Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call.
For example the following C++ function print() is tail recursive.
C
// An example of tail recursive functionÂ
void print(int n){Â Â Â Â if (n < 0)Â Â Â Â Â Â Â Â return;Â Â Â Â printf("%d ", n);Â
    // The last executed statement is recursive call    print(n - 1);} |
C++
// An example of tail recursive functionÂ
static void print(int n){    if (n < 0)        return;    cout << " " << n;      // The last executed statement is recursive call    print(n - 1);}Â
// This code is contributed by Aman Kumar |
Java
// An example of tail recursive functionÂ
static void print(int n){Â Â Â Â if (n < 0)Â Â Â Â Â Â Â Â return;Â
    System.out.print(" " + n);Â
    // The last executed statement    // is recursive call    print(n - 1);}Â
// This code is contributed by divyeh072019 |
Python3
# An example of tail recursive functionÂ
Â
def prints(n):Â
    if (n < 0):        return    print(str(n), end=' ')Â
    # The last executed statement is recursive call    prints(n-1)Â
    # This code is contributed by Pratham76    # improved by ashish2021 |
C#
// An example of tail recursive functionÂ
static void print(int n){Â Â Â Â if (n < 0)Â Â Â Â Â Â Â Â return;Â
    Console.Write(" " + n);Â
    // The last executed statement    // is recursive call    print(n - 1);}Â
// This code is contributed by divyeshrabadiya07 |
Javascript
<script>// An example of tail recursive function function print(n) {     if (n < 0)       return;         document.write(" " + n);         // The last executed statement       // is recursive call     print(n - 1); } Â
// This code is contributed by Rajput-Ji</script> |
Time Complexity: O(n)
Auxiliary Space: O(n)
Need for Tail Recursion:
The tail recursive functions are considered better than non-tail recursive functions as tail-recursion can be optimized by the compiler.Â
Compilers usually execute recursive procedures by using a stack. This stack consists of all the pertinent information, including the parameter values, for each recursive call. When a procedure is called, its information is pushed onto a stack, and when the function terminates the information is popped out of the stack. Thus for the non-tail-recursive functions, the stack depth (maximum amount of stack space used at any time during compilation) is more.Â
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 (See this for more details).
Can a non-tail-recursive function be written as tail-recursive to optimize it?
Consider the following function to calculate the factorial of n.Â
It is a non-tail-recursive function. Although it looks like a tail recursive at first look. If we take a closer look, we can see that the value returned by fact(n-1) is used in fact(n). So the call to fact(n-1) is not the last thing done by fact(n).
C++
#include <iostream>using namespace std;Â
// A NON-tail-recursive function. The function is not tail// recursive because the value returned by fact(n-1) is used// in fact(n) and call to fact(n-1) is not the last thing// done by fact(n)unsigned int fact(unsigned int n){    if (n <= 0)        return 1;Â
    return n * fact(n - 1);}Â
// Driver program to test above functionint main(){Â Â Â Â cout << fact(5);Â Â Â Â return 0;} |
Java
class GFG {Â
    // A NON-tail-recursive function.    // The function is not tail    // recursive because the value    // returned by fact(n-1) is used    // in fact(n) and call to fact(n-1)    // is not the last thing done by    // fact(n)    static int fact(int n)    {        if (n == 0)            return 1;Â
        return n * fact(n - 1);    }Â
    // Driver program    public static void main(String[] args)    {        System.out.println(fact(5));    }}Â
// This code is contributed by Smitha. |
Python3
# A NON-tail-recursive function.# The function is not tail# recursive because the value# returned by fact(n-1) is used# in fact(n) and call to fact(n-1)# is not the last thing done by# fact(n)Â
Â
def fact(n):Â Â Â Â if (n == 0):Â Â Â Â Â Â Â Â return 1Â Â Â Â return n * fact(n-1)Â
Â
# Driver program to test# above functionif __name__ == '__main__':Â Â Â Â print(fact(5))Â
# This code is contributed by Smitha. |
C#
using System;Â
class GFG {Â
    // A NON-tail-recursive function.    // The function is not tail    // recursive because the value    // returned by fact(n-1) is used    // in fact(n) and call to fact(n-1)    // is not the last thing done by    // fact(n)    static int fact(int n)    {        if (n == 0)            return 1;Â
        return n * fact(n - 1);    }Â
    // Driver program to test    // above function    public static void Main() { Console.Write(fact(5)); }}Â
// This code is contributed by Smitha |
PHP
<?php// A NON-tail-recursive function. // The function is not tail// recursive because the value // returned by fact(n-1) is used in// fact(n) and call to fact(n-1) is// not the last thing done by fact(n)Â
function fact( $n){Â Â Â Â if ($n == 0) return 1;Â
    return $n * fact($n - 1);}Â
    // Driver Code    echo fact(5);Â
// This code is contributed by Ajit?> |
Javascript
<script>Â
// A NON-tail-recursive function.// The function is not tail// recursive because the value// returned by fact(n-1) is used// in fact(n) and call to fact(n-1)// is not the last thing done by// fact(n)function fact(n){Â Â Â Â if (n == 0)Â Â Â Â Â Â Â Â return 1;Â Â Â Â Â Â return n * fact(n - 1);}Â
// Driver codedocument.write(fact(5));Â
// This code is contributed by divyeshrabadiya07Â
</script> |
120
Time Complexity: O(n)
Auxiliary Space: O(n)
The above function can be written as a tail-recursive function. The idea is to use one more argument and accumulate the factorial value in the second argument. When n reaches 0, return the accumulated value.
Below is the implementation using a tail-recursive function.
C++
#include <iostream>using namespace std;Â
// A tail recursive function to calculate factorialunsigned factTR(unsigned int n, unsigned int a){Â Â Â Â if (n <= 1)Â Â Â Â Â Â Â Â return a;Â
    return factTR(n - 1, n * a);}Â
// A wrapper over factTRunsigned int fact(unsigned int n) { return factTR(n, 1); }Â
// Driver program to test above functionint main(){Â Â Â Â cout << fact(5);Â Â Â Â return 0;} |
Java
// Java Code for Tail RecursionÂ
class GFG {Â
    // A tail recursive function    // to calculate factorial    static int factTR(int n, int a)    {        if (n <= 0)            return a;Â
        return factTR(n - 1, n * a);    }Â
    // A wrapper over factTR    static int fact(int n) { return factTR(n, 1); }Â
    // Driver code    static public void main(String[] args)    {        System.out.println(fact(5));    }}Â
// This code is contributed by Smitha. |
Python3
# A tail recursive function# to calculate factorialÂ
Â
def fact(n, a=1):Â
    if (n <= 1):        return aÂ
    return fact(n - 1, n * a)Â
Â
# Driver program to test# above functionprint(fact(5))Â
# This code is contributed# by Smitha# improved by Ujwal, ashish2021 |
C#
// C# Code for Tail RecursionÂ
using System;Â
class GFG {Â
    // A tail recursive function    // to calculate factorial    static int factTR(int n, int a)    {        if (n <= 0)            return a;Â
        return factTR(n - 1, n * a);    }Â
    // A wrapper over factTR    static int fact(int n) { return factTR(n, 1); }Â
    // Driver code    static public void Main()    {        Console.WriteLine(fact(5));    }}Â
// This code is contributed by Ajit. |
PHP
<?phpÂ
// A tail recursive function// to calculate factorialfunction factTR($n, $a){Â Â Â Â if ($n <= 0) return $a;Â
    return factTR($n - 1, $n * $a);}Â
// A wrapper over factTRfunction fact($n){Â Â Â Â return factTR($n, 1);}Â
// Driver program to test // above functionecho fact(5);Â
// This code is contributed// by Smitha?> |
Javascript
<script>Â
// Javascript Code for Tail RecursionÂ
// A tail recursive function// to calculate factorialfunction factTR(n, a){Â Â Â Â if (n <= 0)Â Â Â Â Â Â Â Â return a;Â Â Â Â Â Â return factTR(n - 1, n * a);}Â Â // A wrapper over factTRfunction fact(n){Â Â Â Â return factTR(n, 1);}Â
// Driver code document.write(fact(5));Â
// This code is contributed by rameshtravel07Â Â Â Â Â </script> |
120
Time Complexity: O(n)
Auxiliary Space: O(1)
Next articles on this topic:Â
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed aboveÂ
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



