SlideShare a Scribd company logo
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.
Ad

More Related Content

What's hot (20)

Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler Design
Kuppusamy P
 
Amortized Analysis of Algorithms
Amortized Analysis of Algorithms Amortized Analysis of Algorithms
Amortized Analysis of Algorithms
sathish sak
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
Sujan Mia
 
Recursion in c
Recursion in cRecursion in c
Recursion in c
Saket Pathak
 
Lexical analyzer generator lex
Lexical analyzer generator lexLexical analyzer generator lex
Lexical analyzer generator lex
Anusuya123
 
Code optimization in compiler design
Code optimization in compiler designCode optimization in compiler design
Code optimization in compiler design
Kuppusamy P
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
Tail recursion
Tail recursionTail recursion
Tail recursion
SOURAVBHUNIA11
 
Recursion
RecursionRecursion
Recursion
Abdur Rehman
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
Then Murugeshwari
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 
Topological Sorting
Topological SortingTopological Sorting
Topological Sorting
ShahDhruv21
 
Functions in python
Functions in python Functions in python
Functions in python
baabtra.com - No. 1 supplier of quality freshers
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
RubaNagarajan
 
C program compiler presentation
C program compiler presentationC program compiler presentation
C program compiler presentation
Rigvendra Kumar Vardhan
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
Vraj Patel
 
Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
Sachin Sharma
 
File in C language
File in C languageFile in C language
File in C language
Manash Kumar Mondal
 

Viewers also liked (7)

Recursion in c++
Recursion in c++Recursion in c++
Recursion in c++
Abdul Rehman
 
Recursion Pattern Analysis and Feedback
Recursion Pattern Analysis and FeedbackRecursion Pattern Analysis and Feedback
Recursion Pattern Analysis and Feedback
Sander Mak (@Sander_Mak)
 
1 Recur
1 Recur1 Recur
1 Recur
Carlos Delgado Kloos
 
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
9. Searching & Sorting - Data Structures using C++ by Varsha Patil9. Searching & Sorting - Data Structures using C++ by Varsha Patil
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIATypes Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Dheeraj Kataria
 
4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
9. Searching & Sorting - Data Structures using C++ by Varsha Patil9. Searching & Sorting - Data Structures using C++ by Varsha Patil
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIATypes Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Dheeraj Kataria
 
4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
Ad

Similar to Tail recursion (20)

Recursion in C
Recursion in CRecursion in C
Recursion in C
v_jk
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
ssuser823678
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
ssuser2076d9
 
functionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.ppt
functionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.pptfunctionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.ppt
functionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.ppt
RoselinLourd
 
function_v1fgdfdf5645ythyth6ythythgbg.ppt
function_v1fgdfdf5645ythyth6ythythgbg.pptfunction_v1fgdfdf5645ythyth6ythythgbg.ppt
function_v1fgdfdf5645ythyth6ythythgbg.ppt
RoselinLourd
 
functions
functionsfunctions
functions
Makwana Bhavesh
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptx
Dr. Chandrakant Divate
 
Function in c
Function in cFunction in c
Function in c
Raj Tandukar
 
Function in c
Function in cFunction in c
Function in c
CGC Technical campus,Mohali
 
Function C++
Function C++ Function C++
Function C++
Shahzad Afridi
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
Sampath Kumar
 
UNIT3.pptx
UNIT3.pptxUNIT3.pptx
UNIT3.pptx
NagasaiT
 
C function
C functionC function
C function
thirumalaikumar3
 
Functionssssssssssssssssssssssssssss.pdf
Functionssssssssssssssssssssssssssss.pdfFunctionssssssssssssssssssssssssssss.pdf
Functionssssssssssssssssssssssssssss.pdf
bodzzaa21
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
Saranya saran
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
Rumman Ansari
 
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONSPPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
Sitamarhi Institute of Technology
 
Recursion
RecursionRecursion
Recursion
Nikxjon
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
alish sha
 
Function
Function Function
Function
Kathmandu University
 
Recursion in C
Recursion in CRecursion in C
Recursion in C
v_jk
 
functionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.ppt
functionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.pptfunctionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.ppt
functionsamplejfjfjfjfjfhjfjfhjfgjfg_v1.ppt
RoselinLourd
 
function_v1fgdfdf5645ythyth6ythythgbg.ppt
function_v1fgdfdf5645ythyth6ythythgbg.pptfunction_v1fgdfdf5645ythyth6ythythgbg.ppt
function_v1fgdfdf5645ythyth6ythythgbg.ppt
RoselinLourd
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptx
Dr. Chandrakant Divate
 
UNIT3.pptx
UNIT3.pptxUNIT3.pptx
UNIT3.pptx
NagasaiT
 
Functionssssssssssssssssssssssssssss.pdf
Functionssssssssssssssssssssssssssss.pdfFunctionssssssssssssssssssssssssssss.pdf
Functionssssssssssssssssssssssssssss.pdf
bodzzaa21
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
Saranya saran
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
Rumman Ansari
 
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONSPPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
Sitamarhi Institute of Technology
 
Recursion
RecursionRecursion
Recursion
Nikxjon
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
alish sha
 
Ad

More from Rumman Ansari (20)

Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
Rumman Ansari
 
C programming exercises and solutions
C programming exercises and solutions C programming exercises and solutions
C programming exercises and solutions
Rumman Ansari
 
Java Tutorial best website
Java Tutorial best websiteJava Tutorial best website
Java Tutorial best website
Rumman Ansari
 
Java Questions and Answers
Java Questions and AnswersJava Questions and Answers
Java Questions and Answers
Rumman Ansari
 
servlet programming
servlet programmingservlet programming
servlet programming
Rumman Ansari
 
C program to write c program without using main function
C program to write c program without using main functionC program to write c program without using main function
C program to write c program without using main function
Rumman Ansari
 
Steps for c program execution
Steps for c program executionSteps for c program execution
Steps for c program execution
Rumman Ansari
 
Pointer in c program
Pointer in c programPointer in c program
Pointer in c program
Rumman Ansari
 
My first program in c, hello world !
My first program in c, hello world !My first program in c, hello world !
My first program in c, hello world !
Rumman Ansari
 
How c program execute in c program
How c program execute in c program How c program execute in c program
How c program execute in c program
Rumman Ansari
 
What is token c programming
What is token c programmingWhat is token c programming
What is token c programming
Rumman Ansari
 
What is identifier c programming
What is identifier c programmingWhat is identifier c programming
What is identifier c programming
Rumman Ansari
 
What is keyword in c programming
What is keyword in c programmingWhat is keyword in c programming
What is keyword in c programming
Rumman Ansari
 
Type casting in c programming
Type casting in c programmingType casting in c programming
Type casting in c programming
Rumman Ansari
 
C Programming Language Part 11
C Programming Language Part 11C Programming Language Part 11
C Programming Language Part 11
Rumman Ansari
 
C Programming Language Part 9
C Programming Language Part 9C Programming Language Part 9
C Programming Language Part 9
Rumman Ansari
 
C Programming Language Part 8
C Programming Language Part 8C Programming Language Part 8
C Programming Language Part 8
Rumman Ansari
 
C Programming Language Part 6
C Programming Language Part 6C Programming Language Part 6
C Programming Language Part 6
Rumman Ansari
 
C Programming Language Part 5
C Programming Language Part 5C Programming Language Part 5
C Programming Language Part 5
Rumman Ansari
 
C Programming Language Part 4
C Programming Language Part 4C Programming Language Part 4
C Programming Language Part 4
Rumman Ansari
 
C programming exercises and solutions
C programming exercises and solutions C programming exercises and solutions
C programming exercises and solutions
Rumman Ansari
 
Java Tutorial best website
Java Tutorial best websiteJava Tutorial best website
Java Tutorial best website
Rumman Ansari
 
Java Questions and Answers
Java Questions and AnswersJava Questions and Answers
Java Questions and Answers
Rumman Ansari
 
C program to write c program without using main function
C program to write c program without using main functionC program to write c program without using main function
C program to write c program without using main function
Rumman Ansari
 
Steps for c program execution
Steps for c program executionSteps for c program execution
Steps for c program execution
Rumman Ansari
 
Pointer in c program
Pointer in c programPointer in c program
Pointer in c program
Rumman Ansari
 
My first program in c, hello world !
My first program in c, hello world !My first program in c, hello world !
My first program in c, hello world !
Rumman Ansari
 
How c program execute in c program
How c program execute in c program How c program execute in c program
How c program execute in c program
Rumman Ansari
 
What is token c programming
What is token c programmingWhat is token c programming
What is token c programming
Rumman Ansari
 
What is identifier c programming
What is identifier c programmingWhat is identifier c programming
What is identifier c programming
Rumman Ansari
 
What is keyword in c programming
What is keyword in c programmingWhat is keyword in c programming
What is keyword in c programming
Rumman Ansari
 
Type casting in c programming
Type casting in c programmingType casting in c programming
Type casting in c programming
Rumman Ansari
 
C Programming Language Part 11
C Programming Language Part 11C Programming Language Part 11
C Programming Language Part 11
Rumman Ansari
 
C Programming Language Part 9
C Programming Language Part 9C Programming Language Part 9
C Programming Language Part 9
Rumman Ansari
 
C Programming Language Part 8
C Programming Language Part 8C Programming Language Part 8
C Programming Language Part 8
Rumman Ansari
 
C Programming Language Part 6
C Programming Language Part 6C Programming Language Part 6
C Programming Language Part 6
Rumman Ansari
 
C Programming Language Part 5
C Programming Language Part 5C Programming Language Part 5
C Programming Language Part 5
Rumman Ansari
 
C Programming Language Part 4
C Programming Language Part 4C Programming Language Part 4
C Programming Language Part 4
Rumman Ansari
 

Recently uploaded (20)

Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 
Personal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.pptPersonal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.ppt
ganjangbegu579
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
Guru Nanak Technical Institutions
 
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic AlgorithmDesign Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Journal of Soft Computing in Civil Engineering
 
David Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And PythonDavid Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And Python
David Boutry
 
Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
Frontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend EngineersFrontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend Engineers
Michael Hertzberg
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
SanjeetMishra29
 
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
ijdmsjournal
 
acid base ppt and their specific application in food
acid base ppt and their specific application in foodacid base ppt and their specific application in food
acid base ppt and their specific application in food
Fatehatun Noor
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Deepfake Phishing: A New Frontier in Cyber Threats
Deepfake Phishing: A New Frontier in Cyber ThreatsDeepfake Phishing: A New Frontier in Cyber Threats
Deepfake Phishing: A New Frontier in Cyber Threats
RaviKumar256934
 
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Journal of Soft Computing in Civil Engineering
 
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdfATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ssuserda39791
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 
Personal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.pptPersonal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.ppt
ganjangbegu579
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
David Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And PythonDavid Boutry - Specializes In AWS, Microservices And Python
David Boutry - Specializes In AWS, Microservices And Python
David Boutry
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
Frontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend EngineersFrontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend Engineers
Michael Hertzberg
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
🚀 TDX Bengaluru 2025 Unwrapped: Key Highlights, Innovations & Trailblazer Tak...
SanjeetMishra29
 
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
OPTIMIZING DATA INTEROPERABILITY IN AGILE ORGANIZATIONS: INTEGRATING NONAKA’S...
ijdmsjournal
 
acid base ppt and their specific application in food
acid base ppt and their specific application in foodacid base ppt and their specific application in food
acid base ppt and their specific application in food
Fatehatun Noor
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Deepfake Phishing: A New Frontier in Cyber Threats
Deepfake Phishing: A New Frontier in Cyber ThreatsDeepfake Phishing: A New Frontier in Cyber Threats
Deepfake Phishing: A New Frontier in Cyber Threats
RaviKumar256934
 
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdfATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ssuserda39791
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 

Tail recursion

  • 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.
  翻译: