SlideShare a Scribd company logo
2
Most read
4
Most read
10
Most read
Tail
Recursion
What is tail recursion?
A recursive function call is tail recursive when recursive call is the last thing
executed by the function.
A recursive function call is said to be tail recursive if there is nothing to do
after the function returns except return its value.
/* non tail recursive example of the
factorial function in C*/
#include<stdio.h>
void main(){
int c;
c=factorial(5);
printf("%dn",c);
}
factorial(n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
// A tail recursive function to calculate factorial
#include<stdio.h>
void main(){
int c;
c=factorial(5);
printf("%dn",c);
}
fact(n, result) {
if (n == 0) return result;
return fact(n - 1, n * result);
}
factorial(n) {
return fact(n, 1);
}
Recursive procedures call themselves to work towards a solution
to a problem. In simple implementations this balloons the stack
as the nesting gets deeper and deeper, reaches the solution,
then returns through all of the stack frames. This waste is a
common complaint about recursive programming in general.
Why do we care?
The tail recursive functions considered better than non tail
recursive functions as tail-recursion can be optimized by
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 is of no use.
/* tail-recursion of factorial1 can be equivalently
defined in terms of goto: */
#include<stdio.h>
void main(){
int c;
c=factorial(5,1);
printf("%dn",c);
}
factorial(n, accumulator) {
beginning:
if (n == 0) return accumulator;
else {
accumulator *= n;
n -= 1;
goto beginning;
}
}
/* the goto version, we can derive a version
that uses C's built-in control structures:*/
#include<stdio.h>
void main(){
int c;
c=factorial1(5,1);
printf("%dn",c);
}
factorial1(n, accumulator) {
while (n != 0) {
accumulator *= n;
n -= 1;
}
return accumulator;
}
/* the goto version, we can derive a version
that uses C's built-in control structures:*/
#include<stdio.h>
void main(){
int c;
c=factorial1(5,1);
printf("%dn",c);
}
factorial1(n, accumulator) {
while (n != 0) {
accumulator *= n;
n -= 1;
}
return accumulator;
}
Advantages of tail recursion:
In traditional recursion, you perform your recursive calls first, and then you take the return value of the
recursive call and calculate the result. So you have to wait till you return from every recursive call for
result.
In tail recursion, you perform your calculations first, and then you execute the recursive call, passing the
results of your current step to the next recursive step.
In this way once you are ready to perform your next recursive step, you don't need the current stack
frame any more. This way your program is optimised a lot.
The tail recursive functions considered better than non tail recursive functions as tail-recursion can be
optimized by 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 is of no use.
Tail call
A tail call is the last call executed in a function; if a tail call leads to the
parent function being invoked again, then the function is tail recursive.
The tail recursive function does not use the stack; the function calculates the
factorial as it goes along! The last recursive call performs a simple
calculation based on the input arguments and returns.
Thus, there is no need to push frames on to the stack because the new
function already has everything it needs. As such stack overflows would not
occur with tail call optimized functions.
Tail call
The biggest advantage of using tail calls is that they allow you to do
extensive operations without exceeding the call stack. This makes it possible
to do a lot of work in constant space without running into out of memory
exceptions; this happens because the frame for the currently executing
function is re-used by the newly-executed function call.
It is possible to write the same function using tail call recursion and this will
allow you to do it for arbitrarily large values. The space optimization is
from O(n) to O(1) since every new function call reuses existing frames rather
than pushing stuff on the stack.

More Related Content

PPTX
6-Python-Recursion PPT.pptx
PPTX
[OOP - Lec 19] Static Member Functions
PDF
PPT
Expression evaluation
PPTX
Conversion of Infix to Prefix and Postfix with Stack
PPT
Application of Stacks
PPTX
Inline function
PDF
Access specifiers (Public Private Protected) C++
6-Python-Recursion PPT.pptx
[OOP - Lec 19] Static Member Functions
Expression evaluation
Conversion of Infix to Prefix and Postfix with Stack
Application of Stacks
Inline function
Access specifiers (Public Private Protected) C++

What's hot (20)

PPT
Queue implementation
PPTX
Ppt of operations on one way link list
PPT
Data Structures- Part5 recursion
PDF
Constructors and destructors
PPT
Removal Of Recursion
PPT
Shell programming
PPT
C++ Arrays
PPTX
Stack using Array
PPT
Queue Data Structure
PPTX
Lecture 14 run time environment
PPTX
Three Address code
PPSX
Files in c++
PPTX
Functions in c
PPTX
Methods in java
PPTX
Constructor and destructor
PPTX
Storage classes in c language
PDF
Java threads
PPT
RECURSION IN C
PPT
Memory allocation in c
PPTX
Input-Buffering
Queue implementation
Ppt of operations on one way link list
Data Structures- Part5 recursion
Constructors and destructors
Removal Of Recursion
Shell programming
C++ Arrays
Stack using Array
Queue Data Structure
Lecture 14 run time environment
Three Address code
Files in c++
Functions in c
Methods in java
Constructor and destructor
Storage classes in c language
Java threads
RECURSION IN C
Memory allocation in c
Input-Buffering
Ad

Viewers also liked (20)

PPTX
україна едина країна1
PPTX
Smoking kills........by majid rabbani
PDF
Abdul Ghaffar and Sons Overseas Employment
PDF
Work lifeleader Manifesto
PPTX
Kearifan Lokal tentang Pencemaran limbah di Sungai perkampungan pondok manggis
PPTX
Deployable Disaster Device
PPT
поширення отруєння грибами. профілактика харчових отруєнь
PDF
employer-brand-playbook-us-en
PDF
Inchiesta pubblica per saturnia
DOC
торгівля людьми забороняється законом україни
PDF
час і досі не загоїв рани, цей
PDF
JACM2636_JacMax Lindsay Book Email FA
PDF
Variazioni ATC per domenica 12 aprile
DOC
Comunicato stampa piano spiagge Marinella
PPTX
Bai trinh dien_gioi_thieu_bai_day
PDF
Final PDF Paper 3-6-12
PPTX
Proiect de lecţie
україна едина країна1
Smoking kills........by majid rabbani
Abdul Ghaffar and Sons Overseas Employment
Work lifeleader Manifesto
Kearifan Lokal tentang Pencemaran limbah di Sungai perkampungan pondok manggis
Deployable Disaster Device
поширення отруєння грибами. профілактика харчових отруєнь
employer-brand-playbook-us-en
Inchiesta pubblica per saturnia
торгівля людьми забороняється законом україни
час і досі не загоїв рани, цей
JACM2636_JacMax Lindsay Book Email FA
Variazioni ATC per domenica 12 aprile
Comunicato stampa piano spiagge Marinella
Bai trinh dien_gioi_thieu_bai_day
Final PDF Paper 3-6-12
Proiect de lecţie
Ad

Similar to Tail Recursion in data structure (20)

PPT
Recursion in C
PPT
function_v1.ppt
PPT
function_v1.ppt
PPT
functionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.ppt
PPT
function_v1fgdfdf5645ythyth6ythythgbg.ppt
PPTX
functions
PPTX
Fundamentals of functions in C program.pptx
PPTX
Function in c
PPTX
PPTX
Function C++
PPTX
Functionincprogram
PPTX
UNIT3.pptx
PPTX
C function
PDF
Functionssssssssssssssssssssssssssss.pdf
PPT
Functions and pointers_unit_4
PPTX
C Programming Language Part 7
DOCX
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
PDF
Recursion
PPTX
Dti2143 chapter 5
PDF
Recursion in C
function_v1.ppt
function_v1.ppt
functionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.ppt
function_v1fgdfdf5645ythyth6ythythgbg.ppt
functions
Fundamentals of functions in C program.pptx
Function in c
Function C++
Functionincprogram
UNIT3.pptx
C function
Functionssssssssssssssssssssssssssss.pdf
Functions and pointers_unit_4
C Programming Language Part 7
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
Recursion
Dti2143 chapter 5

More from Rumman Ansari (20)

PDF
Sql tutorial
PDF
C programming exercises and solutions
PDF
Java Tutorial best website
DOCX
Java Questions and Answers
DOCX
servlet programming
PPTX
C program to write c program without using main function
PPTX
Steps for c program execution
PPTX
Pointer in c program
PPTX
My first program in c, hello world !
PPTX
How c program execute in c program
PPTX
What is token c programming
PPTX
What is identifier c programming
PPTX
What is keyword in c programming
PPTX
Type casting in c programming
PPTX
C Programming Language Part 11
PPTX
C Programming Language Part 9
PPTX
C Programming Language Part 8
PPTX
C Programming Language Part 6
PPTX
C Programming Language Part 5
PPTX
C Programming Language Part 4
Sql tutorial
C programming exercises and solutions
Java Tutorial best website
Java Questions and Answers
servlet programming
C program to write c program without using main function
Steps for c program execution
Pointer in c program
My first program in c, hello world !
How c program execute in c program
What is token c programming
What is identifier c programming
What is keyword in c programming
Type casting in c programming
C Programming Language Part 11
C Programming Language Part 9
C Programming Language Part 8
C Programming Language Part 6
C Programming Language Part 5
C Programming Language Part 4

Recently uploaded (20)

PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
Construction Project Organization Group 2.pptx
PDF
PPT on Performance Review to get promotions
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
Sustainable Sites - Green Building Construction
PPTX
web development for engineering and engineering
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
additive manufacturing of ss316l using mig welding
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
composite construction of structures.pdf
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
Well-logging-methods_new................
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
UNIT 4 Total Quality Management .pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
Structs to JSON How Go Powers REST APIs.pdf
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Operating System & Kernel Study Guide-1 - converted.pdf
Construction Project Organization Group 2.pptx
PPT on Performance Review to get promotions
Embodied AI: Ushering in the Next Era of Intelligent Systems
Sustainable Sites - Green Building Construction
web development for engineering and engineering
CH1 Production IntroductoryConcepts.pptx
additive manufacturing of ss316l using mig welding
Model Code of Practice - Construction Work - 21102022 .pdf
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
composite construction of structures.pdf
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Well-logging-methods_new................
CYBER-CRIMES AND SECURITY A guide to understanding
UNIT 4 Total Quality Management .pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Structs to JSON How Go Powers REST APIs.pdf

Tail Recursion in data structure

  • 2. What is tail recursion? A recursive function call is tail recursive when recursive call is the last thing executed by the function. A recursive function call is said to be tail recursive if there is nothing to do after the function returns except return its value.
  • 3. /* non tail recursive example of the factorial function in C*/ #include<stdio.h> void main(){ int c; c=factorial(5); printf("%dn",c); } factorial(n) { if (n == 0) return 1; return n * factorial(n - 1); }
  • 4. // A tail recursive function to calculate factorial #include<stdio.h> void main(){ int c; c=factorial(5); printf("%dn",c); } fact(n, result) { if (n == 0) return result; return fact(n - 1, n * result); } factorial(n) { return fact(n, 1); }
  • 5. Recursive procedures call themselves to work towards a solution to a problem. In simple implementations this balloons the stack as the nesting gets deeper and deeper, reaches the solution, then returns through all of the stack frames. This waste is a common complaint about recursive programming in general.
  • 6. Why do we care? The tail recursive functions considered better than non tail recursive functions as tail-recursion can be optimized by 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 is of no use.
  • 7. /* tail-recursion of factorial1 can be equivalently defined in terms of goto: */ #include<stdio.h> void main(){ int c; c=factorial(5,1); printf("%dn",c); } factorial(n, accumulator) { beginning: if (n == 0) return accumulator; else { accumulator *= n; n -= 1; goto beginning; } }
  • 8. /* the goto version, we can derive a version that uses C's built-in control structures:*/ #include<stdio.h> void main(){ int c; c=factorial1(5,1); printf("%dn",c); } factorial1(n, accumulator) { while (n != 0) { accumulator *= n; n -= 1; } return accumulator; }
  • 9. /* the goto version, we can derive a version that uses C's built-in control structures:*/ #include<stdio.h> void main(){ int c; c=factorial1(5,1); printf("%dn",c); } factorial1(n, accumulator) { while (n != 0) { accumulator *= n; n -= 1; } return accumulator; }
  • 10. Advantages of tail recursion: In traditional recursion, you perform your recursive calls first, and then you take the return value of the recursive call and calculate the result. So you have to wait till you return from every recursive call for result. In tail recursion, you perform your calculations first, and then you execute the recursive call, passing the results of your current step to the next recursive step. In this way once you are ready to perform your next recursive step, you don't need the current stack frame any more. This way your program is optimised a lot. The tail recursive functions considered better than non tail recursive functions as tail-recursion can be optimized by 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 is of no use.
  • 11. Tail call A tail call is the last call executed in a function; if a tail call leads to the parent function being invoked again, then the function is tail recursive. The tail recursive function does not use the stack; the function calculates the factorial as it goes along! The last recursive call performs a simple calculation based on the input arguments and returns. Thus, there is no need to push frames on to the stack because the new function already has everything it needs. As such stack overflows would not occur with tail call optimized functions.
  • 12. Tail call The biggest advantage of using tail calls is that they allow you to do extensive operations without exceeding the call stack. This makes it possible to do a lot of work in constant space without running into out of memory exceptions; this happens because the frame for the currently executing function is re-used by the newly-executed function call. It is possible to write the same function using tail call recursion and this will allow you to do it for arbitrarily large values. The space optimization is from O(n) to O(1) since every new function call reuses existing frames rather than pushing stuff on the stack.