SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Recursion
Lecturer Najia Manjur
Department of Computer Science and Engineering
Military Institute of Science and Technology
Recursive Function
• The recursive function is
– a kind of function that calls itself
• Recursion is a technique that solves a problem by
solving a smaller version of the same function.
Problems Suitable for Recursive Functions
• The problem can be reduced entirely to simple cases by
calling the recursive function.
• One or more simple cases of the problem have a
straightforward solution.
• The other cases can be redefined in terms of problems
that are closer to the simple cases.
– If this is a simple case
solve it
else
redefine the problem using recursion
Example of Recursion: Factorial
• Recursive implementation
int Factorial(int n)
{
if (n==0) // simple case
return 1;
else
return n * Factorial(n-1);
}
Trace of Recursion: Factorial
5!
5*4!
4*3!
3*2!
2*1!
1*0!
1 1
1*0!
2*1!
3*2!
4*3!
5*4!
5!
1 is returned
1*1=1 is returned
2*1=2 is returned
3*2=6 is returned
4*6=24 is returned
5*24=120 is returned
Coding the Factorial function (cont.)
• Iterative implementation
int Factorial(int n)
{
int fact = 1;
for(int count = 2; count <= n; count++)
fact = fact * count;
return fact;
}
Recursion vs. iteration
• Iteration can be used in place of recursion
– An iterative algorithm uses a looping construct
– A recursive algorithm uses a branching structure
• Recursive solutions are often less efficient, in
terms of both time and space, than iterative
solutions
• Recursion can simplify the solution of a problem,
often resulting in shorter, more easily understood
source code
Example of Recursion
n choose k (combinations)
• Given n things, how many different sets of
size k can be chosen?
𝑛
𝑘
= 𝑛−1
𝑘
+ 𝑛−1
𝑘−1
, 1<k<n
with base cases:
𝑛
1
= 𝑛 𝑘 = 1 , 𝑛
𝑛
= 1 (𝑘 = 𝑛)
int Combinations(int n, int k)
{
if(k == 1) // base case 1
return n;
else if (n == k) // base case 2
return 1;
else
return(Combinations(n-1, k) + Combinations(n-1, k-1));
}
n choose k (combinations)
How to write a recursive function?
• Determine the base case(s)
(the one for which you know the answer)
• Verify the algorithm
(use the "Three-Question-Method")
• Determine the general case(s)
(the one where the problem is expressed as a
smaller version of itself)
Three-Question Verification Method
1. The Base-Case Question:
Is there a non-recursive way out of the function,
and does the routine work correctly for this
"base" case?
2. The Smaller-Caller Question:
Does each recursive call to the function involve a
smaller case of the original problem, leading to
the base case?
3. The General-Case Question:
Assuming that the recursive call(s) work
correctly, does the whole function work
correctly?
Example of Recursive Function : Multiply
• We can implement the multiplication by addition.
The simple case is “m*1=m.”
The recursive step uses the following
equation: “m*n = m+m*(n-1).”
Trace of Function multiply(6,3)
The simple case.
The recursive step.
The recursive step.
Terminating Condition
• The recursive functions always contains one or
more terminating conditions.
– A condition when a recursive function is processing
a simple case instead of processing recursion.
• Without the terminating condition, the recursive
function may run forever.
– e.g., in the previous multiply function, the if
statement “if (n == 1) …” is the terminating
condition.
How C Maintains the Recursive Steps
• C keeps track of the values of variables by the
stack data structure.
– Stack is a data structure where the last item added is
the first item processed.
– There are two operations (push and pop) associated
with stack.
a
b
c
b
c
d
b
c
pop a push d
How C Maintains the Recursive Steps
• Each time a function is called, the execution
state of the caller function (e.g., parameters,
local variables, and memory address) are pushed
onto the stack.
• When the execution of the called function is
finished, the execution can be restored by
popping up the execution state from the stack.
• This is sufficient to maintain the execution of the
recursive function.
– The execution state of each recursive step are stored
and kept in order in the stack.
How to Trace Recursive Functions
• The recursive function is not easy to trace and to
debug.
– If there are hundreds of recursive steps, it is not useful
to set the breaking point or to trace step-by-step.
• A naïve but useful approach is inserting printing
statements and then watching the output to trace
the recursive steps.
Watch the input arguments
passed into each recursive step.
Recursive fibonacci Function
Recursive gcd Function
the greatest common divisor (GCD) of two integers m and
n can be defined recursively.
– gcd(m,n) is n if n divides m evenly;
– gcd(m,n) is gcd(n, remainder of m divided by n) otherwise.

Weitere ähnliche Inhalte

Was ist angesagt?

Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C ProgrammingKamal Acharya
 
Data structures & algorithms lecture 3
Data structures & algorithms lecture 3Data structures & algorithms lecture 3
Data structures & algorithms lecture 3Poojith Chowdhary
 
Syntax directed translation
Syntax directed translationSyntax directed translation
Syntax directed translationAkshaya Arunan
 
design and analysis of algorithm Lab files
design and analysis of algorithm Lab filesdesign and analysis of algorithm Lab files
design and analysis of algorithm Lab filesNitesh Dubey
 
Lecture 2 data structures and algorithms
Lecture 2 data structures and algorithmsLecture 2 data structures and algorithms
Lecture 2 data structures and algorithmsAakash deep Singhal
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance HaskellJohan Tibell
 
Ada lab manual
Ada lab manualAda lab manual
Ada lab manualaman713418
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structurekalyanineve
 
Pattern printing-in-c(Jaydip Kikani)
Pattern printing-in-c(Jaydip Kikani)Pattern printing-in-c(Jaydip Kikani)
Pattern printing-in-c(Jaydip Kikani)Jaydip JK
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by ExampleOlve Maudal
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocationvaani pathak
 
Object Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesObject Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesFellowBuddy.com
 

Was ist angesagt? (20)

Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C Programming
 
Input-Buffering
Input-BufferingInput-Buffering
Input-Buffering
 
Data structures & algorithms lecture 3
Data structures & algorithms lecture 3Data structures & algorithms lecture 3
Data structures & algorithms lecture 3
 
c-programming
c-programmingc-programming
c-programming
 
Introduction to Input/Output Functions in C
Introduction to Input/Output Functions in CIntroduction to Input/Output Functions in C
Introduction to Input/Output Functions in C
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 
Syntax directed translation
Syntax directed translationSyntax directed translation
Syntax directed translation
 
Module 11
Module 11Module 11
Module 11
 
design and analysis of algorithm Lab files
design and analysis of algorithm Lab filesdesign and analysis of algorithm Lab files
design and analysis of algorithm Lab files
 
Lecture 2 data structures and algorithms
Lecture 2 data structures and algorithmsLecture 2 data structures and algorithms
Lecture 2 data structures and algorithms
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
 
Ada lab manual
Ada lab manualAda lab manual
Ada lab manual
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
 
Pattern printing-in-c(Jaydip Kikani)
Pattern printing-in-c(Jaydip Kikani)Pattern printing-in-c(Jaydip Kikani)
Pattern printing-in-c(Jaydip Kikani)
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Circular queues
Circular queuesCircular queues
Circular queues
 
CPU INPUT OUTPUT
CPU INPUT OUTPUT CPU INPUT OUTPUT
CPU INPUT OUTPUT
 
Dynamic Memory Allocation
Dynamic Memory AllocationDynamic Memory Allocation
Dynamic Memory Allocation
 
Object Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesObject Oriented Programming Lecture Notes
Object Oriented Programming Lecture Notes
 
Recursion
RecursionRecursion
Recursion
 

Andere mochten auch

Reunião de pais 21032017 2 e 3 º anos
Reunião de pais  21032017 2 e 3 º anosReunião de pais  21032017 2 e 3 º anos
Reunião de pais 21032017 2 e 3 º anosAlexandre Misturini
 
презентація до відкритого уроку читання «Весна йде та йде» за Марко Вовчок, ...
презентація до відкритого уроку читання «Весна йде та йде» за Марко Вовчок,  ...презентація до відкритого уроку читання «Весна йде та йде» за Марко Вовчок,  ...
презентація до відкритого уроку читання «Весна йде та йде» за Марко Вовчок, ...Irina0912
 
Film industry task 5
Film industry task 5Film industry task 5
Film industry task 5Josh Yates
 
Video Editing Resume
Video Editing ResumeVideo Editing Resume
Video Editing ResumeKevin Sandera
 
OpenZFS novel algorithms: snapshots, space allocation, RAID-Z - Matt Ahrens
OpenZFS novel algorithms: snapshots, space allocation, RAID-Z - Matt AhrensOpenZFS novel algorithms: snapshots, space allocation, RAID-Z - Matt Ahrens
OpenZFS novel algorithms: snapshots, space allocation, RAID-Z - Matt AhrensMatthew Ahrens
 
конспект відкритого уроку читання «Весна йде та йде» за Марко Вовчок, «Прихо...
конспект відкритого уроку читання «Весна йде та йде» за Марко Вовчок,  «Прихо...конспект відкритого уроку читання «Весна йде та йде» за Марко Вовчок,  «Прихо...
конспект відкритого уроку читання «Весна йде та йде» за Марко Вовчок, «Прихо...Irina0912
 
Monitoring Network Performance in China
Monitoring Network Performance in ChinaMonitoring Network Performance in China
Monitoring Network Performance in ChinaThousandEyes
 
Top Reasons to learn Digital Marketing
Top Reasons to learn Digital Marketing Top Reasons to learn Digital Marketing
Top Reasons to learn Digital Marketing digitalpiller
 
Audience feedback of my magazine SIMRAN KAUR
Audience feedback of my magazine SIMRAN KAURAudience feedback of my magazine SIMRAN KAUR
Audience feedback of my magazine SIMRAN KAURAS Media Column E
 
Introduction aux leçons
Introduction aux leçonsIntroduction aux leçons
Introduction aux leçonsPierrot Caron
 
Crowdfunding x Scholarship
Crowdfunding x ScholarshipCrowdfunding x Scholarship
Crowdfunding x ScholarshipSimon Douw
 
Project tiger and wild life conservation in india
Project tiger and wild life conservation in indiaProject tiger and wild life conservation in india
Project tiger and wild life conservation in indiaDeepali Dhiware
 
Präsentation Eingangsstufe GS Staakenweg
Präsentation Eingangsstufe GS StaakenwegPräsentation Eingangsstufe GS Staakenweg
Präsentation Eingangsstufe GS StaakenwegGrundschuleStaakenweg
 
Казка "Струмок"
Казка "Струмок"Казка "Струмок"
Казка "Струмок"Olya Yavorivska
 
Mercadotecnia y Promoción de la Salud. Heberto Priego
Mercadotecnia y Promoción de la Salud. Heberto PriegoMercadotecnia y Promoción de la Salud. Heberto Priego
Mercadotecnia y Promoción de la Salud. Heberto PriegoHeberto Priego
 

Andere mochten auch (18)

Reunião de pais 21032017 2 e 3 º anos
Reunião de pais  21032017 2 e 3 º anosReunião de pais  21032017 2 e 3 º anos
Reunião de pais 21032017 2 e 3 º anos
 
презентація до відкритого уроку читання «Весна йде та йде» за Марко Вовчок, ...
презентація до відкритого уроку читання «Весна йде та йде» за Марко Вовчок,  ...презентація до відкритого уроку читання «Весна йде та йде» за Марко Вовчок,  ...
презентація до відкритого уроку читання «Весна йде та йде» за Марко Вовчок, ...
 
Film industry task 5
Film industry task 5Film industry task 5
Film industry task 5
 
Frederico garcia lorca definitiu ok
Frederico garcia lorca definitiu okFrederico garcia lorca definitiu ok
Frederico garcia lorca definitiu ok
 
Video Editing Resume
Video Editing ResumeVideo Editing Resume
Video Editing Resume
 
OpenZFS novel algorithms: snapshots, space allocation, RAID-Z - Matt Ahrens
OpenZFS novel algorithms: snapshots, space allocation, RAID-Z - Matt AhrensOpenZFS novel algorithms: snapshots, space allocation, RAID-Z - Matt Ahrens
OpenZFS novel algorithms: snapshots, space allocation, RAID-Z - Matt Ahrens
 
11plus workbook s
11plus workbook s11plus workbook s
11plus workbook s
 
конспект відкритого уроку читання «Весна йде та йде» за Марко Вовчок, «Прихо...
конспект відкритого уроку читання «Весна йде та йде» за Марко Вовчок,  «Прихо...конспект відкритого уроку читання «Весна йде та йде» за Марко Вовчок,  «Прихо...
конспект відкритого уроку читання «Весна йде та йде» за Марко Вовчок, «Прихо...
 
Monitoring Network Performance in China
Monitoring Network Performance in ChinaMonitoring Network Performance in China
Monitoring Network Performance in China
 
Top Reasons to learn Digital Marketing
Top Reasons to learn Digital Marketing Top Reasons to learn Digital Marketing
Top Reasons to learn Digital Marketing
 
Audience feedback of my magazine SIMRAN KAUR
Audience feedback of my magazine SIMRAN KAURAudience feedback of my magazine SIMRAN KAUR
Audience feedback of my magazine SIMRAN KAUR
 
Introduction aux leçons
Introduction aux leçonsIntroduction aux leçons
Introduction aux leçons
 
Crowdfunding x Scholarship
Crowdfunding x ScholarshipCrowdfunding x Scholarship
Crowdfunding x Scholarship
 
Project tiger and wild life conservation in india
Project tiger and wild life conservation in indiaProject tiger and wild life conservation in india
Project tiger and wild life conservation in india
 
0394827198
03948271980394827198
0394827198
 
Präsentation Eingangsstufe GS Staakenweg
Präsentation Eingangsstufe GS StaakenwegPräsentation Eingangsstufe GS Staakenweg
Präsentation Eingangsstufe GS Staakenweg
 
Казка "Струмок"
Казка "Струмок"Казка "Струмок"
Казка "Струмок"
 
Mercadotecnia y Promoción de la Salud. Heberto Priego
Mercadotecnia y Promoción de la Salud. Heberto PriegoMercadotecnia y Promoción de la Salud. Heberto Priego
Mercadotecnia y Promoción de la Salud. Heberto Priego
 

Ähnlich wie Recursion

Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting AlgorithmsAfaq Mansoor Khan
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursionAbdullah Al-hazmy
 
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory AccessAccelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory AccessIgor Sfiligoi
 
Recursion and looping
Recursion and loopingRecursion and looping
Recursion and loopingxcoolanurag
 
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx15AnasKhan
 
Reinforcement Learning and Artificial Neural Nets
Reinforcement Learning and Artificial Neural NetsReinforcement Learning and Artificial Neural Nets
Reinforcement Learning and Artificial Neural NetsPierre de Lacaze
 
lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptxLizhen Shi
 
CS8451 - Design and Analysis of Algorithms
CS8451 - Design and Analysis of AlgorithmsCS8451 - Design and Analysis of Algorithms
CS8451 - Design and Analysis of AlgorithmsKrishnan MuthuManickam
 
Complexity Analysis of Recursive Function
Complexity Analysis of Recursive FunctionComplexity Analysis of Recursive Function
Complexity Analysis of Recursive FunctionMeghaj Mallick
 
Module 01 Stack and Recursion
Module 01 Stack and RecursionModule 01 Stack and Recursion
Module 01 Stack and RecursionTushar B Kute
 
Dsoop (co 221) 1
Dsoop (co 221) 1Dsoop (co 221) 1
Dsoop (co 221) 1Puja Koch
 
Unit-I Recursion.pptx
Unit-I Recursion.pptxUnit-I Recursion.pptx
Unit-I Recursion.pptxajajkhan16
 

Ähnlich wie Recursion (20)

Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting Algorithms
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory AccessAccelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
 
Recursion and looping
Recursion and loopingRecursion and looping
Recursion and looping
 
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
 
RecursionWeek8.ppt
RecursionWeek8.pptRecursionWeek8.ppt
RecursionWeek8.ppt
 
Reinforcement Learning and Artificial Neural Nets
Reinforcement Learning and Artificial Neural NetsReinforcement Learning and Artificial Neural Nets
Reinforcement Learning and Artificial Neural Nets
 
Knapsack problem using fixed tuple
Knapsack problem using fixed tupleKnapsack problem using fixed tuple
Knapsack problem using fixed tuple
 
lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptx
 
recursion.ppt
recursion.pptrecursion.ppt
recursion.ppt
 
CS8451 - Design and Analysis of Algorithms
CS8451 - Design and Analysis of AlgorithmsCS8451 - Design and Analysis of Algorithms
CS8451 - Design and Analysis of Algorithms
 
6-Python-Recursion.pdf
6-Python-Recursion.pdf6-Python-Recursion.pdf
6-Python-Recursion.pdf
 
Complexity Analysis of Recursive Function
Complexity Analysis of Recursive FunctionComplexity Analysis of Recursive Function
Complexity Analysis of Recursive Function
 
Module 01 Stack and Recursion
Module 01 Stack and RecursionModule 01 Stack and Recursion
Module 01 Stack and Recursion
 
Ppt chapter12
Ppt chapter12Ppt chapter12
Ppt chapter12
 
Dsoop (co 221) 1
Dsoop (co 221) 1Dsoop (co 221) 1
Dsoop (co 221) 1
 
Unit-I Recursion.pptx
Unit-I Recursion.pptxUnit-I Recursion.pptx
Unit-I Recursion.pptx
 
recursion.ppt
recursion.pptrecursion.ppt
recursion.ppt
 
RECURSION.pptx
RECURSION.pptxRECURSION.pptx
RECURSION.pptx
 
algo_vc_lecture8.ppt
algo_vc_lecture8.pptalgo_vc_lecture8.ppt
algo_vc_lecture8.ppt
 

Mehr von Jesmin Akhter (8)

Lecture 11
Lecture  11Lecture  11
Lecture 11
 
Lecture 10
Lecture  10Lecture  10
Lecture 10
 
Lecture 11
Lecture  11Lecture  11
Lecture 11
 
Lecture 10
Lecture  10Lecture  10
Lecture 10
 
1605.01126
1605.011261605.01126
1605.01126
 
Lecture 05 2017
Lecture 05 2017Lecture 05 2017
Lecture 05 2017
 
Lecture 01 2017
Lecture 01 2017Lecture 01 2017
Lecture 01 2017
 
Functions
FunctionsFunctions
Functions
 

Kürzlich hochgeladen

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 

Kürzlich hochgeladen (20)

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 

Recursion

  • 1. Recursion Lecturer Najia Manjur Department of Computer Science and Engineering Military Institute of Science and Technology
  • 2. Recursive Function • The recursive function is – a kind of function that calls itself • Recursion is a technique that solves a problem by solving a smaller version of the same function.
  • 3. Problems Suitable for Recursive Functions • The problem can be reduced entirely to simple cases by calling the recursive function. • One or more simple cases of the problem have a straightforward solution. • The other cases can be redefined in terms of problems that are closer to the simple cases. – If this is a simple case solve it else redefine the problem using recursion
  • 4. Example of Recursion: Factorial • Recursive implementation int Factorial(int n) { if (n==0) // simple case return 1; else return n * Factorial(n-1); }
  • 5. Trace of Recursion: Factorial 5! 5*4! 4*3! 3*2! 2*1! 1*0! 1 1 1*0! 2*1! 3*2! 4*3! 5*4! 5! 1 is returned 1*1=1 is returned 2*1=2 is returned 3*2=6 is returned 4*6=24 is returned 5*24=120 is returned
  • 6. Coding the Factorial function (cont.) • Iterative implementation int Factorial(int n) { int fact = 1; for(int count = 2; count <= n; count++) fact = fact * count; return fact; }
  • 7. Recursion vs. iteration • Iteration can be used in place of recursion – An iterative algorithm uses a looping construct – A recursive algorithm uses a branching structure • Recursive solutions are often less efficient, in terms of both time and space, than iterative solutions • Recursion can simplify the solution of a problem, often resulting in shorter, more easily understood source code
  • 8. Example of Recursion n choose k (combinations) • Given n things, how many different sets of size k can be chosen? 𝑛 𝑘 = 𝑛−1 𝑘 + 𝑛−1 𝑘−1 , 1<k<n with base cases: 𝑛 1 = 𝑛 𝑘 = 1 , 𝑛 𝑛 = 1 (𝑘 = 𝑛)
  • 9. int Combinations(int n, int k) { if(k == 1) // base case 1 return n; else if (n == k) // base case 2 return 1; else return(Combinations(n-1, k) + Combinations(n-1, k-1)); } n choose k (combinations)
  • 10.
  • 11. How to write a recursive function? • Determine the base case(s) (the one for which you know the answer) • Verify the algorithm (use the "Three-Question-Method") • Determine the general case(s) (the one where the problem is expressed as a smaller version of itself)
  • 12. Three-Question Verification Method 1. The Base-Case Question: Is there a non-recursive way out of the function, and does the routine work correctly for this "base" case? 2. The Smaller-Caller Question: Does each recursive call to the function involve a smaller case of the original problem, leading to the base case? 3. The General-Case Question: Assuming that the recursive call(s) work correctly, does the whole function work correctly?
  • 13. Example of Recursive Function : Multiply • We can implement the multiplication by addition. The simple case is “m*1=m.” The recursive step uses the following equation: “m*n = m+m*(n-1).”
  • 14. Trace of Function multiply(6,3) The simple case. The recursive step. The recursive step.
  • 15. Terminating Condition • The recursive functions always contains one or more terminating conditions. – A condition when a recursive function is processing a simple case instead of processing recursion. • Without the terminating condition, the recursive function may run forever. – e.g., in the previous multiply function, the if statement “if (n == 1) …” is the terminating condition.
  • 16. How C Maintains the Recursive Steps • C keeps track of the values of variables by the stack data structure. – Stack is a data structure where the last item added is the first item processed. – There are two operations (push and pop) associated with stack. a b c b c d b c pop a push d
  • 17. How C Maintains the Recursive Steps • Each time a function is called, the execution state of the caller function (e.g., parameters, local variables, and memory address) are pushed onto the stack. • When the execution of the called function is finished, the execution can be restored by popping up the execution state from the stack. • This is sufficient to maintain the execution of the recursive function. – The execution state of each recursive step are stored and kept in order in the stack.
  • 18. How to Trace Recursive Functions • The recursive function is not easy to trace and to debug. – If there are hundreds of recursive steps, it is not useful to set the breaking point or to trace step-by-step. • A naïve but useful approach is inserting printing statements and then watching the output to trace the recursive steps. Watch the input arguments passed into each recursive step.
  • 20. Recursive gcd Function the greatest common divisor (GCD) of two integers m and n can be defined recursively. – gcd(m,n) is n if n divides m evenly; – gcd(m,n) is gcd(n, remainder of m divided by n) otherwise.