SlideShare a Scribd company logo
2
Most read
10
Most read
11
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

PDF
Problem solving
PPT
Data Structures- Part5 recursion
PDF
Hill climbing algorithm in artificial intelligence
PPTX
LL(1) parsing
PPTX
CLOSEST PAIR (Final)
PPTX
AI_Session 7 Greedy Best first search algorithm.pptx
PPTX
Tail Recursion in data structure
Problem solving
Data Structures- Part5 recursion
Hill climbing algorithm in artificial intelligence
LL(1) parsing
CLOSEST PAIR (Final)
AI_Session 7 Greedy Best first search algorithm.pptx
Tail Recursion in data structure

What's hot (20)

PPTX
Generating code from dags
PPT
Binary search tree(bst)
PPTX
Function overloading and overriding
PPTX
First and follow set
PPTX
PPTX
Analysis of algorithm
PPT
Pre defined Functions in C
PPT
Greedy Algorithms Huffman Coding.ppt
PPTX
Inline function
PDF
Code optimization in compiler design
PPT
Depth First Search ( DFS )
PPT
Recurrences
PPTX
Recursion
PDF
Little o and little omega
PPT
Lecture 4 - Growth of Functions (1).ppt
PPTX
Formatted Console I/O Operations in C++
PPTX
Code generation
PPT
Lecture 14 - Scope Rules
PPT
Unit 3 principles of programming language
PPT
16 virtual function
Generating code from dags
Binary search tree(bst)
Function overloading and overriding
First and follow set
Analysis of algorithm
Pre defined Functions in C
Greedy Algorithms Huffman Coding.ppt
Inline function
Code optimization in compiler design
Depth First Search ( DFS )
Recurrences
Recursion
Little o and little omega
Lecture 4 - Growth of Functions (1).ppt
Formatted Console I/O Operations in C++
Code generation
Lecture 14 - Scope Rules
Unit 3 principles of programming language
16 virtual function
Ad

Viewers also liked (6)

PPTX
Recursion in c++
PDF
Recursion Pattern Analysis and Feedback
PPTX
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
PPTX
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
PPTX
4. Recursion - Data Structures using C++ by Varsha Patil
Recursion in c++
Recursion Pattern Analysis and Feedback
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
4. Recursion - Data Structures using C++ by Varsha Patil
Ad

Similar to Tail recursion (20)

PPTX
Tail recursion
PDF
Recursion
PPTX
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
PDF
12200224070_Adnan_Ahmed_DAAbhbhbh_63.pdf
PPTX
Function & Recursion
PDF
Recursion For the Rest of Us (CS Fundamentals Series)
PPTX
Unit-I Recursion.pptx
PPTX
Recursive Function
PPT
recursion.ppt
ODP
C workshop day 6
PPTX
Recursion is used in programming languages to use a procedure multiple times ...
PPTX
ECE2102-Week10-11-Recursion-Conclusion.pptx
PPTX
Recursion
PPT
Lecture 12 - Recursion
PPTX
Recursion
PPTX
3-Recursive Function in programming .pptx
PPT
Recursion and looping
PDF
[ITP - Lecture 14] Recursion
PPTX
Recursion And Implementation C Programming
PPTX
Tail call optimization (TCO) - Lecture
Tail recursion
Recursion
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
12200224070_Adnan_Ahmed_DAAbhbhbh_63.pdf
Function & Recursion
Recursion For the Rest of Us (CS Fundamentals Series)
Unit-I Recursion.pptx
Recursive Function
recursion.ppt
C workshop day 6
Recursion is used in programming languages to use a procedure multiple times ...
ECE2102-Week10-11-Recursion-Conclusion.pptx
Recursion
Lecture 12 - Recursion
Recursion
3-Recursive Function in programming .pptx
Recursion and looping
[ITP - Lecture 14] Recursion
Recursion And Implementation C Programming
Tail call optimization (TCO) - Lecture

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 7
PPTX
C Programming Language Part 6
PPTX
C Programming Language Part 5
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 7
C Programming Language Part 6
C Programming Language Part 5

Recently uploaded (20)

PPTX
additive manufacturing of ss316l using mig welding
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
Construction Project Organization Group 2.pptx
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
Well-logging-methods_new................
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
composite construction of structures.pdf
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
additive manufacturing of ss316l using mig welding
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Construction Project Organization Group 2.pptx
Lecture Notes Electrical Wiring System Components
Internet of Things (IOT) - A guide to understanding
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Well-logging-methods_new................
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
composite construction of structures.pdf
OOP with Java - Java Introduction (Basics)
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...

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.