SlideShare a Scribd company logo
1 of 20
Download to read offline
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.

More Related Content

What's hot

What's hot (20)

Complexity analysis in Algorithms
Complexity analysis in AlgorithmsComplexity analysis in Algorithms
Complexity analysis in Algorithms
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysis
 
Complexity of Algorithm
Complexity of AlgorithmComplexity of Algorithm
Complexity of Algorithm
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
 
Data structures
Data structuresData structures
Data structures
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
AI_Session 11: searching with Non-Deterministic Actions and partial observati...
AI_Session 11: searching with Non-Deterministic Actions and partial observati...AI_Session 11: searching with Non-Deterministic Actions and partial observati...
AI_Session 11: searching with Non-Deterministic Actions and partial observati...
 
Theory of Computation
Theory of ComputationTheory of Computation
Theory of Computation
 
Operator precedance parsing
Operator precedance parsingOperator precedance parsing
Operator precedance parsing
 
Algorithms Lecture 2: Analysis of Algorithms I
Algorithms Lecture 2: Analysis of Algorithms IAlgorithms Lecture 2: Analysis of Algorithms I
Algorithms Lecture 2: Analysis of Algorithms I
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
Circular queue
Circular queueCircular queue
Circular queue
 
stack & queue
stack & queuestack & queue
stack & queue
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
 
Stack
StackStack
Stack
 
Big O Notation
Big O NotationBig O Notation
Big O Notation
 
Hash table
Hash tableHash table
Hash table
 

Viewers also liked

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
 

Viewers also liked (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
 

Similar to 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
 

Similar to Recursion (20)

Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting Algorithms
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 
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
 

More from 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
 

Recently uploaded

CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 
LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF NAT...
LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF  NAT...LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF  NAT...
LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF NAT...pragatimahajan3
 
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...EduSkills OECD
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...Nguyen Thanh Tu Collection
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptxmary850239
 
How to create _name_search function in odoo 17
How to create _name_search function in odoo 17How to create _name_search function in odoo 17
How to create _name_search function in odoo 17Celine George
 
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEPART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEMISSRITIMABIOLOGYEXP
 
What is Property Fields in Odoo 17 ERP Module
What is Property Fields in Odoo 17 ERP ModuleWhat is Property Fields in Odoo 17 ERP Module
What is Property Fields in Odoo 17 ERP ModuleCeline George
 
Supply agency market - aiming high 2.pdf
Supply agency market - aiming high 2.pdfSupply agency market - aiming high 2.pdf
Supply agency market - aiming high 2.pdftomeskell101
 
How to Share Dashboard in the Odoo 17 ERP
How to Share Dashboard in the Odoo 17 ERPHow to Share Dashboard in the Odoo 17 ERP
How to Share Dashboard in the Odoo 17 ERPCeline George
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Osopher
 
647291105-Ppt-Arts-10-4th-Quarter-1.pdfi
647291105-Ppt-Arts-10-4th-Quarter-1.pdfi647291105-Ppt-Arts-10-4th-Quarter-1.pdfi
647291105-Ppt-Arts-10-4th-Quarter-1.pdfijoemmbrillantes
 
16. Discovery, function and commercial uses of different PGRS.pptx
16. Discovery, function and commercial uses of different PGRS.pptx16. Discovery, function and commercial uses of different PGRS.pptx
16. Discovery, function and commercial uses of different PGRS.pptxUmeshTimilsina1
 
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...DrVipulVKapoor
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxMadhavi Dharankar
 
4.4.24 Economic Precarity and Global Economic Forces.pptx
4.4.24 Economic Precarity and Global Economic Forces.pptx4.4.24 Economic Precarity and Global Economic Forces.pptx
4.4.24 Economic Precarity and Global Economic Forces.pptxmary850239
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroomSamsung Business USA
 

Recently uploaded (20)

CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 
LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF NAT...
LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF  NAT...LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF  NAT...
LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF NAT...
 
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx
 
How to create _name_search function in odoo 17
How to create _name_search function in odoo 17How to create _name_search function in odoo 17
How to create _name_search function in odoo 17
 
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEPART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
 
What is Property Fields in Odoo 17 ERP Module
What is Property Fields in Odoo 17 ERP ModuleWhat is Property Fields in Odoo 17 ERP Module
What is Property Fields in Odoo 17 ERP Module
 
Supply agency market - aiming high 2.pdf
Supply agency market - aiming high 2.pdfSupply agency market - aiming high 2.pdf
Supply agency market - aiming high 2.pdf
 
How to Share Dashboard in the Odoo 17 ERP
How to Share Dashboard in the Odoo 17 ERPHow to Share Dashboard in the Odoo 17 ERP
How to Share Dashboard in the Odoo 17 ERP
 
CARNAVAL COM MAGIA E EUFORIA _
CARNAVAL COM MAGIA E EUFORIA            _CARNAVAL COM MAGIA E EUFORIA            _
CARNAVAL COM MAGIA E EUFORIA _
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
 
647291105-Ppt-Arts-10-4th-Quarter-1.pdfi
647291105-Ppt-Arts-10-4th-Quarter-1.pdfi647291105-Ppt-Arts-10-4th-Quarter-1.pdfi
647291105-Ppt-Arts-10-4th-Quarter-1.pdfi
 
16. Discovery, function and commercial uses of different PGRS.pptx
16. Discovery, function and commercial uses of different PGRS.pptx16. Discovery, function and commercial uses of different PGRS.pptx
16. Discovery, function and commercial uses of different PGRS.pptx
 
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptx
 
4.4.24 Economic Precarity and Global Economic Forces.pptx
4.4.24 Economic Precarity and Global Economic Forces.pptx4.4.24 Economic Precarity and Global Economic Forces.pptx
4.4.24 Economic Precarity and Global Economic Forces.pptx
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom
 

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.