VOOZH about

URL: https://www.geeksforgeeks.org/dsa/tail-recursion/

⇱ Tail Recursion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Tail Recursion

Last Updated : 20 Jan, 2026

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.

Need for Tail Recursion:

  • Tail-recursive functions are better than non-tail-recursive ones because they can be optimized by the compiler.
  • 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 can be avoided by simply sending the control back to the beginning of the function either using a loop or goto statement.(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).


Output
120

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.


Output
120

Next articles on this topic:

Comment