 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Tail Recursion in Data Structures
Here we will see what is tail recursion. The tail recursion is basically using the recursive function as the last statement of the function. So when nothing is left to do after coming back from the recursive call, that is called tail recursion. We will see one example of tail recursion.
Example
#include <iostream> using namespace std; void printN(int n){    if(n < 0){       return;    }    cout << n << " ";    printN(n - 1); } int main() {    printN(10); }  Output
10 9 8 7 6 5 4 3 2 1 0
The tail recursion is better than non-tail recursion. As there is no task left after the recursive call, it will be easier for the compiler to optimize the code. When one function is called, its address is stored inside the stack. So if it is tail recursion, then storing addresses into stack is not needed.
We can use factorial using recursion, but the function is not tail recursive. The value of fact(n-1) is used inside the fact(n).
long fact(int n){    if(n <= 1)       return 1;    n * fact(n-1); } We can make it tail recursive, by adding some other parameters. This is like below −
long fact(long n, long a){    if(n == 0)       return a;    return fact(n-1, a*n); }