SlideShare a Scribd company logo
Advanced Data Structure
Recursion
Presented by:-A.RAVINDRA KUMAR RAO
(B.TECH (C.E))
Madanapalle Institute Of Technology & Science
CONTENTS
 RECURSION
 RECURSIVE ALGORITHMAS
 RECURSIVE TYPES
 RECURSIVE FUNCTIONS
 RECURSIVE DATATYPES
 ORDER OF EXECUTION
 EXAMPLE
RECURSION
What is recursion?
It’s when a function calls itself.
how does this happen?
When we talk about recursion, we are really talking about creating a loop.
Let’s start by looking at a basic loop.
for(int i=0; i<10;i++)
{
cout<<“the number is:”<<i<< end1;
}
Output:
the number is :0
the number is:1
the number is:2
the number is:3
RECURSIVE ALGORITHM
Implementation and use of Recursive Algorithms:
 space for all local, automatic (not static) variables
 space for all formal parameters
 the return address
 any other system information about the function or the function that called it.
 The function must have a selection construct which caters for the base case
 The recursive call must deal with a simpler/smaller version of the data
 Recursion uses selection construct and achieves repetition through repeated function
calls.
 Recursion has a base case.
 Any problem that can be solved recursively can be solved iteratively.
RECURSIVE ALGORITHM
A recursive algorithm is an algorithm which calls itself with "smaller or simpler"
input values, and which obtains the result for the current input by applying simple
operations to the returned value for the smaller input.
Example 1: Algorithm for finding the k-th even natural number
Algorithm 1: Even(positive integer k)
Input: k , a positive integer
Output: k-th even natural number (the first even being 0)
if k = 1,
then return 0;
else
return Even(k-1) + 2 .
RECURSIVE TYPES
Single recursion:
Recursion that only contains a single self-reference is
known as single recursion.
Example: Factorial function.
Multiple recursion:
Recursion that contains multiple self-references is known as
multiple recursion.
Ex: Fibonacci sequence
Direct recursion:
In which a function calls itself.
Ex: ƒ calls ƒ i.e. direct recursion
Indirect recursion:
Indirect recursion occurs when a function is called not by
itself but by another function that it called (either directly or
indirectly).
Ex: ƒ calls g, which calls ƒ
RECURSIVE TYPES
Anonymous recursion:
Recursion is usually done by explicitly calling a function by name.
However, recursion can also be done via implicitly calling a function based on
the current context, which is particularly useful for anonymous function and
is known as anonymous recursion.
Structural Recursion:
Functions that consume structured data, typically decompose their
arguments into their immediate structural components and then process
those components. If one of the immediate components belongs to the same
class of data as the input, the function is recursive.
EX: Factorial.
Generative Recursion:
Many well-known recursive algorithms generate an entirely new
piece of data from the given data and recur on it.
Ex: GCD, Binary Search
RECURSIVE FUNCTION
RECURSION FUNCTION:
Recursion is often seen as an efficient method of programming since it
requires the least amount of code to perform the necessary functions. However,
recursion must be incorporated carefully, since it can lead to an infinite loop if no
condition is met that will terminate the function.
MATHMATICAL FUNCTION:
In mathematics we often define a function in terms of itself.
For example: The factorial function f(n)=n!, for n is an integer, is defined as follows;
ƒ(n)={1 n≤1
{ n ƒ(n-1) n>1
TAIL RECURSIVE: In a tail-recursive function, none of the recursive call do
additional work after the recursive call is complete (additional work includes
printing, etc), except to return the value of the recursive call.
return rec_func( x, y ) ; // no work after recursive call, just return the
value of call
MUTUALLY RECURSIVE: For example, function f() can call function g() and
function g() can call function f(). This is still considered recursion because a
function can eventually call itself. In this case, f() indirectly calls itself.
RECURSIVE FUNCTIONS
FACTORIAL FUNCTION:
int Fact(int n)
{
if (n == 0)
{
return 1;
}
else
{
return n * Fact(n - 1);
}
}
RECURSIVE FUNCTION
RECURSIVE DATA TYPES
Inductively defined data:
An inductively defined recursive data definition is one that
specifies how to construct instances of the data.
Ex: linked list.
Co-inductively defined data type:
A co-inductive data definition is one that specifies the operations
that may be performed on a piece of data.
A co-inductive definition of infinite streams of strings
Ex: A stream of strings is an object s such that head(s) is a string,
and tail(s) is a stream of strings.
ORDER OF EXECUTION
In the simple case of a function calling itself only once, instructions placed before the
recursive call are executed once per recursion before any of the instructions placed
after the recursive call. The latter are executed repeatedly after the maximum
recursion has been reached.
Function 1
void recursiveFunction(int num)
{
printf("%dn", num);
if (num < 4)
recursiveFunction(num + 1);
}
ORDER OF EXECUTION
Function 2 with swapped lines:
void recursiveFunction(int num) {
if (num < 4)
recursiveFunction(num + 1);
printf("%dn", num);
}
SYSTEM STACK OF RECURSION
OBJECT HEAP
UNUSED
MEMORY
CALL STACK
STATIC VARS
BYTECODES
OS / JVM
Method n
Activation on Record
. . . .
Method 3
Activation on Record
Method 2
Activation on Record
Method 1
Activation on Record
LOCAL VARS
PARAMETERS
RETURN ADDRESS
(PC Values)
PREVIOUS BASE
POINTER
RETURN VALUE
BASE POINTER
PROGRAM COUNTER
REAL TIME EXAMPLE
(Recursion)ads

More Related Content

What's hot

Recursion and looping
Recursion and loopingRecursion and looping
Recursion and looping
xcoolanurag
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructures
Nguync91368
 
Iterations and Recursions
Iterations and RecursionsIterations and Recursions
Iterations and Recursions
Abdul Rahman Sherzad
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
Chapter 7 ds
Chapter 7 dsChapter 7 ds
Chapter 7 ds
Hanif Durad
 
Chapter 4 ds
Chapter 4 dsChapter 4 ds
Chapter 4 ds
Hanif Durad
 
Data Structures- Part2 analysis tools
Data Structures- Part2 analysis toolsData Structures- Part2 analysis tools
Data Structures- Part2 analysis tools
Abdullah Al-hazmy
 
Searching Algorithms
Searching AlgorithmsSearching Algorithms
Searching Algorithms
Afaq Mansoor Khan
 
Chapter 6 ds
Chapter 6 dsChapter 6 ds
Chapter 6 ds
Hanif Durad
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Julie Iskander
 
Data Structure and Algorithms
Data Structure and Algorithms Data Structure and Algorithms
Data Structure and Algorithms
ManishPrajapati78
 
Data Structures- Part1 overview and review
Data Structures- Part1 overview and reviewData Structures- Part1 overview and review
Data Structures- Part1 overview and review
Abdullah Al-hazmy
 
Recursion
RecursionRecursion
Recursion
Malainine Zaid
 
Module 01 Stack and Recursion
Module 01 Stack and RecursionModule 01 Stack and Recursion
Module 01 Stack and Recursion
Tushar B Kute
 
Iteration, induction, and recursion
Iteration, induction, and recursionIteration, induction, and recursion
Iteration, induction, and recursion
Mohammed Hussein
 
Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete  Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete
Adnan abid
 
Introduction to datastructure and algorithm
Introduction to datastructure and algorithmIntroduction to datastructure and algorithm
Introduction to datastructure and algorithm
Pratik Mota
 

What's hot (20)

Recursion and looping
Recursion and loopingRecursion and looping
Recursion and looping
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructures
 
Iterations and Recursions
Iterations and RecursionsIterations and Recursions
Iterations and Recursions
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Chapter 7 ds
Chapter 7 dsChapter 7 ds
Chapter 7 ds
 
Chapter 4 ds
Chapter 4 dsChapter 4 ds
Chapter 4 ds
 
Data structures
Data structuresData structures
Data structures
 
Data Structures- Part2 analysis tools
Data Structures- Part2 analysis toolsData Structures- Part2 analysis tools
Data Structures- Part2 analysis tools
 
Searching Algorithms
Searching AlgorithmsSearching Algorithms
Searching Algorithms
 
Chapter 6 ds
Chapter 6 dsChapter 6 ds
Chapter 6 ds
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Cis435 week04
Cis435 week04Cis435 week04
Cis435 week04
 
Data Structure and Algorithms
Data Structure and Algorithms Data Structure and Algorithms
Data Structure and Algorithms
 
Data Structures- Part1 overview and review
Data Structures- Part1 overview and reviewData Structures- Part1 overview and review
Data Structures- Part1 overview and review
 
Recursion
RecursionRecursion
Recursion
 
Module 01 Stack and Recursion
Module 01 Stack and RecursionModule 01 Stack and Recursion
Module 01 Stack and Recursion
 
Iteration, induction, and recursion
Iteration, induction, and recursionIteration, induction, and recursion
Iteration, induction, and recursion
 
C1320prespost
C1320prespostC1320prespost
C1320prespost
 
Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete  Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete
 
Introduction to datastructure and algorithm
Introduction to datastructure and algorithmIntroduction to datastructure and algorithm
Introduction to datastructure and algorithm
 

Similar to (Recursion)ads

Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
vekariyakashyap
 
Functions
FunctionsFunctions
Functions
Pragnavi Erva
 
Recursion concepts by Divya
Recursion concepts by DivyaRecursion concepts by Divya
Recursion concepts by Divya
Divya Kumari
 
3-Recursion.ppt
3-Recursion.ppt3-Recursion.ppt
3-Recursion.ppt
TrnHuy921814
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
kavitha muneeshwaran
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
Prerna Sharma
 
Recursion.ppt
 Recursion.ppt Recursion.ppt
Recursion.ppt
TalhaHussain58
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
Md. Imran Hossain Showrov
 
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structure
cogaxor346
 
Functions in c
Functions in cFunctions in c
Functions in c
kalavathisugan
 
FUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptxFUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptx
SafnaSaff1
 
4. function
4. function4. function
4. function
Shankar Gangaju
 
Function in c
Function in cFunction in c
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
Sampath Kumar
 
C++ lecture 03
C++   lecture 03C++   lecture 03
C++ lecture 03
HNDE Labuduwa Galle
 
C function
C functionC function
C function
thirumalaikumar3
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
paijitk
 

Similar to (Recursion)ads (20)

Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
 
Function
FunctionFunction
Function
 
Functions
FunctionsFunctions
Functions
 
Recursion concepts by Divya
Recursion concepts by DivyaRecursion concepts by Divya
Recursion concepts by Divya
 
3-Recursion.ppt
3-Recursion.ppt3-Recursion.ppt
3-Recursion.ppt
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
Recursion.ppt
 Recursion.ppt Recursion.ppt
Recursion.ppt
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
 
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structure
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Function in c
Function in cFunction in c
Function in c
 
FUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptxFUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptx
 
4. function
4. function4. function
4. function
 
Function in c
Function in cFunction in c
Function in c
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
C++ lecture 03
C++   lecture 03C++   lecture 03
C++ lecture 03
 
C function
C functionC function
C function
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
 

Recently uploaded

RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 

Recently uploaded (20)

RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 

(Recursion)ads

  • 1. Advanced Data Structure Recursion Presented by:-A.RAVINDRA KUMAR RAO (B.TECH (C.E)) Madanapalle Institute Of Technology & Science
  • 2. CONTENTS  RECURSION  RECURSIVE ALGORITHMAS  RECURSIVE TYPES  RECURSIVE FUNCTIONS  RECURSIVE DATATYPES  ORDER OF EXECUTION  EXAMPLE
  • 3. RECURSION What is recursion? It’s when a function calls itself. how does this happen? When we talk about recursion, we are really talking about creating a loop. Let’s start by looking at a basic loop. for(int i=0; i<10;i++) { cout<<“the number is:”<<i<< end1; } Output: the number is :0 the number is:1 the number is:2 the number is:3
  • 4. RECURSIVE ALGORITHM Implementation and use of Recursive Algorithms:  space for all local, automatic (not static) variables  space for all formal parameters  the return address  any other system information about the function or the function that called it.  The function must have a selection construct which caters for the base case  The recursive call must deal with a simpler/smaller version of the data  Recursion uses selection construct and achieves repetition through repeated function calls.  Recursion has a base case.  Any problem that can be solved recursively can be solved iteratively.
  • 5. RECURSIVE ALGORITHM A recursive algorithm is an algorithm which calls itself with "smaller or simpler" input values, and which obtains the result for the current input by applying simple operations to the returned value for the smaller input. Example 1: Algorithm for finding the k-th even natural number Algorithm 1: Even(positive integer k) Input: k , a positive integer Output: k-th even natural number (the first even being 0) if k = 1, then return 0; else return Even(k-1) + 2 .
  • 6. RECURSIVE TYPES Single recursion: Recursion that only contains a single self-reference is known as single recursion. Example: Factorial function. Multiple recursion: Recursion that contains multiple self-references is known as multiple recursion. Ex: Fibonacci sequence Direct recursion: In which a function calls itself. Ex: ƒ calls ƒ i.e. direct recursion Indirect recursion: Indirect recursion occurs when a function is called not by itself but by another function that it called (either directly or indirectly). Ex: ƒ calls g, which calls ƒ
  • 7. RECURSIVE TYPES Anonymous recursion: Recursion is usually done by explicitly calling a function by name. However, recursion can also be done via implicitly calling a function based on the current context, which is particularly useful for anonymous function and is known as anonymous recursion. Structural Recursion: Functions that consume structured data, typically decompose their arguments into their immediate structural components and then process those components. If one of the immediate components belongs to the same class of data as the input, the function is recursive. EX: Factorial. Generative Recursion: Many well-known recursive algorithms generate an entirely new piece of data from the given data and recur on it. Ex: GCD, Binary Search
  • 8. RECURSIVE FUNCTION RECURSION FUNCTION: Recursion is often seen as an efficient method of programming since it requires the least amount of code to perform the necessary functions. However, recursion must be incorporated carefully, since it can lead to an infinite loop if no condition is met that will terminate the function. MATHMATICAL FUNCTION: In mathematics we often define a function in terms of itself. For example: The factorial function f(n)=n!, for n is an integer, is defined as follows; ƒ(n)={1 n≤1 { n ƒ(n-1) n>1
  • 9. TAIL RECURSIVE: In a tail-recursive function, none of the recursive call do additional work after the recursive call is complete (additional work includes printing, etc), except to return the value of the recursive call. return rec_func( x, y ) ; // no work after recursive call, just return the value of call MUTUALLY RECURSIVE: For example, function f() can call function g() and function g() can call function f(). This is still considered recursion because a function can eventually call itself. In this case, f() indirectly calls itself. RECURSIVE FUNCTIONS
  • 10. FACTORIAL FUNCTION: int Fact(int n) { if (n == 0) { return 1; } else { return n * Fact(n - 1); } } RECURSIVE FUNCTION
  • 11. RECURSIVE DATA TYPES Inductively defined data: An inductively defined recursive data definition is one that specifies how to construct instances of the data. Ex: linked list. Co-inductively defined data type: A co-inductive data definition is one that specifies the operations that may be performed on a piece of data. A co-inductive definition of infinite streams of strings Ex: A stream of strings is an object s such that head(s) is a string, and tail(s) is a stream of strings.
  • 12. ORDER OF EXECUTION In the simple case of a function calling itself only once, instructions placed before the recursive call are executed once per recursion before any of the instructions placed after the recursive call. The latter are executed repeatedly after the maximum recursion has been reached. Function 1 void recursiveFunction(int num) { printf("%dn", num); if (num < 4) recursiveFunction(num + 1); }
  • 13. ORDER OF EXECUTION Function 2 with swapped lines: void recursiveFunction(int num) { if (num < 4) recursiveFunction(num + 1); printf("%dn", num); }
  • 14. SYSTEM STACK OF RECURSION OBJECT HEAP UNUSED MEMORY CALL STACK STATIC VARS BYTECODES OS / JVM Method n Activation on Record . . . . Method 3 Activation on Record Method 2 Activation on Record Method 1 Activation on Record LOCAL VARS PARAMETERS RETURN ADDRESS (PC Values) PREVIOUS BASE POINTER RETURN VALUE BASE POINTER PROGRAM COUNTER