- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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); }
- Related Articles
- Principles of Recursion in Data Structures
- Abstract Data Type in Data Structures
- Kernel Data Structures
- Kinetic Data Structures
- Bernoulli Distribution in Data Structures
- Binomial Distribution in Data Structures
- Geometric Distribution in Data Structures
- Stack ADT in Data Structures
- Adjacency lists in Data Structures
- Inbuilt Data Structures in C#
- Inbuilt Data Structures in Python
- In-built Data Structures in Python
- Correspondence Based Data Structures
- Data objects and Structures
- Operations on Queue in Data Structures
