SlideShare une entreprise Scribd logo
RECURSION
Produced by Mapako M 2
Objectives
• Learn about recursive definitions
• Explore the base case and the general case of a
recursive definition
• Learn about recursive algorithm
• Learn about recursive functions
• Explore how to use recursive functions to implement
recursive
Data Structures Using C++ 3
Recursive Definitions
• Recursion
– Process of solving a problem by reducing it to smaller
versions of itself
– The recursive algorithm must have one or more base
case(s), and the general solurion must eventually be
reduced to a base case
Recursive Definitions (cont’d.)
• Direct solution
– Right side of the equation contains no factorial
notation
• Recursive definition
– A definition in which something is defined in terms of
a smaller version of itself
• Base case
– Case for which the solution is obtained directly
– The case for which the solution can be stated non-
recursively
Data Structures Using C++ 4
Recursive Definitions (cont’d.)
• General(Recursive) case
– Case for which the solution is obtained indirectly
using recursion
– Case for which the solution is expressed in terms of
the smaller version of itself
• Recursive algorithm
– A solution that is expressed in terms of smaller
instances of itself and a base case
– Finds problem solution by reducing problem to
smaller versions of itself
Data Structures Using C++ 5
Data Structures Using C++ 6
Recursive Definitions (cont’d.)
• Recursion insight gained from factorial problem
– Every recursive definition must have one (or more)
base cases
– General case must eventually reduce to a base case
– Base case stops recursion
• Recursive function
– Function that calls itself
Recursive Definitions (cont’d.)
• Recursive function notable comments
– Recursive function has unlimited number of copies of
itself (logically)
– Every call to a recursive function has its own
• Code, set of parameters, local variables
– After completing a particular recursive call
• Control goes back to calling environment (previous call)
• Current (recursive) call must execute completely before
control goes back to the previous call
• Execution in previous call begins from point
immediately following the recursive call
Data Structures Using C++ 7
Data Structures Using C++ 8
Recursive Definitions (cont’d.)
• Direct and indirect recursion
– Directly recursive function
• Calls itself
– Indirectly recursive function
• Calls another function, eventually results in original
function call
• Requires same analysis as direct recursion
• Base cases must be identified, appropriate solutions to
them provided
• Tracing can be tedious
– Tail recursive function
• Last statement executed: the recursive call
Data Structures Using C++ 9
Recursive Definitions (cont’d.)
• Infinite recursion
– Occurs if every recursive call results in another
recursive call
– Executes forever (in theory)
– Call requirements for recursive functions
• System memory for local variables and formal
parameters
• Saving information for transfer back to right caller
– Finite system memory leads to
• Execution until system runs out of memory
• Abnormal termination of infinite recursive function
Data Structures Using C++ 10
Recursive Definitions (cont’d.)
• Requirements to design a recursive function
– Understand problem requirements
– Determine limiting conditions
– Identify base cases, providing direct solution to each
base case
– Identify general cases, providing solution to each
general case in terms of smaller versions of itself
Data Structures Using C++ 11
Factorial
• Recursive function implementing the factorial
function
FIGURE 6-1 Execution of factorial
Data Structures Using C++ 12
Fibonacci Number
• Sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34 . . .
• Given first two numbers (a1 and a2)
– nth number an, n >= 3, of sequence given by: an = an-1
+ an-2
• Recursive function: rFibNum
– Determines desired Fibonacci number
– Parameters: three numbers representing first two
numbers of the Fibonacci sequence and a number n,
the desired nth Fibonacci number
– Returns the nth Fibonacci number in the sequence
Data Structures Using C++ 13
Fibonacci Number (cont’d.)
• Third Fibonacci number
– Sum of first two Fibonacci numbers
• Fourth Fibonacci number in a sequence
– Sum of second and third Fibonacci numbers
• Calculating fourth Fibonacci number
– Add second Fibonacci number and third Fibonacci
number
Data Structures Using C++ 14
Fibonacci Number (cont’d.)
• Recursive algorithm
– Calculates nth Fibonacci number
• a denotes first Fibonacci number
• b denotes second Fibonacci number
• n denotes nth Fibonacci number
• a series of numbers in which each number (
Fibonacci number ) is the sum of the two preceding
numbers. The simplest is the series 1, 1, 2, 3, 5, 8,
etc.
Data Structures Using C++ 15
Fibonacci Number (cont’d.)
• Recursive function implementing algorithm
• Trace code execution
Data Structures Using C++ 16
Fibonacci Number (cont’d.)
FIGURE 6-7 Execution of rFibNum(2, 3, 4)
Data Structures Using C++ 17
Tower of Hanoi
• Object
– Move 64 disks from first needle to third needle
• Rules
– Only one disk can be moved at a time
– Removed disk must be placed on one of the needles
– A larger disk cannot be placed on top of a smaller disk
FIGURE 6-8 Tower of Hanoi problem with three disks
Data Structures Using C++ 18
Tower of Hanoi (cont’d.)
• Case: first needle contains only one disk
– Move disk directly from needle 1 to needle 3
• Case: first needle contains only two disks
– Move first disk from needle 1 to needle 2
– Move second disk from needle 1 to needle 3
– Move first disk from needle 2 to needle 3
• Case: first needle contains three disks
Data Structures Using C++ 19
Tower of Hanoi (cont’d.)
FIGURE 6-9 Solution to Tower of Hanoi problem with three disks
Data Structures Using C++ 20
Tower of Hanoi (cont’d.)
• Generalize problem to the case of 64 disks
– Recursive algorithm in pseudocode
Data Structures Using C++ 21
Tower of Hanoi (cont’d.)
• Generalize problem to the case of 64 disks
– Recursive algorithm in C++
Data Structures Using C++ 22
Tower of Hanoi (cont’d.)
• Analysis of Tower of Hanoi
– Time necessary to move all 64 disks from needle 1 to
needle 3
– Manually: roughly 5 x 1011 years
• Universe is about 15 billion years old (1.5 x 1010)
– Computer: 500 years
• To generate 264 moves at the rate of 1 billion moves per
second
Data Structures Using C++ 23
Converting a Number from Decimal to
Binary
• Convert nonnegative integer in decimal format (base
10) into equivalent binary number (base 2)
• Rightmost bit of x
– Remainder of x after division by two
• Recursive algorithm pseudocode
– Binary(num) denotes binary representation of num
Data Structures Using C++ 24
Converting a Number from Decimal to
Binary (cont’d.)
• Recursive function implementing algorithm
Data Structures Using C++ 25
Converting a Number from Decimal to
Binary (cont’d.)
FIGURE 6-10 Execution of decToBin(13, 2)
Multiply 2 numbers by addition
int multiply (int a,int b)
{
if(b==0)//base case for recursion to stop
return 0;
else return a + multiply(a,b-1);//recursive case }
Data Structures Using C++ 26
• Recursive function implementing algorithm
Computing powers via linear recursion
int calculatePower(int base, int powerRaised)
{ if (powerRaised != 1)
return (base*calculatePower(base,
powerRaised-1));
else return 1;
}
Data Structures Using C++
27
Reversing an array
• Algorithm ReverseArray(A, i, j):
Input: An array A and nonnegative integer indices
i and j
Output: The reversal of the elements in A starting
at index i and ending at j
if i < j then
Swap A[i] and A[j]
ReverseArray(A, i+1, j-1)
return
Data Structures Using C++ 28
Data Structures Using C++ 29
Recursion or Iteration?
• Dependent upon nature of the solution and efficiency
• Efficiency
– Recursion is less efficient in terms of time and space
– Overhead of recursive function: execution time and memory
usage
• Given speed memory of today’s computers, we can depend
more on how programmer envisions solution
– Use of programmer’s time
– Any program that can be written recursively can also be written
iteratively
– Recursion is simpler and more natural for programmer to write
Advantages of recursion
• Recursion is a must to use in some programming
situations like display a list of files of the system
cannot be solved without recursion
• Recursion is very flexible in data structures like
stacks, queues, linked list and quick sort
• Using recursion the length of the program can be
reduced.
• It makes the code easier to read as it reflex our
normal manner of thinking
• It makes a function or a procedure easier to
understand
Data Structures Using C++ 30
Disadvantages of recursion
• May be slower than iteration
• Use greater resources because of extra function
calls
• More difficult to understand in some algorithms. An
algorithm that can be naturally expressed iteratively
may not be easy to understand if expressed
recursively.
• There is no portable way to tell how deep recursion
can go without causing trouble( how much ‘stack
space’ the machine has) and there is no way to
recover from deep recursion( a stack overflow)
Data Structures Using C++ 31
Data Structures Using C++ 32
Summary
• Recursion
– Solve problem by reducing it to smaller versions of
itself
• Recursive algorithms implemented using recursive
functions
– Direct, indirect, and infinite recursion
• Many problems solved using recursive algorithms
• Choosing between recursion and iteration
– Nature of solution; efficiency requirements
• Backtracking
– Problem solving; iterative design technique

Contenu connexe

Tendances

Introduction to design and analysis of algorithm
Introduction to design and analysis of algorithmIntroduction to design and analysis of algorithm
Introduction to design and analysis of algorithm
DevaKumari Vijay
 
Three address code In Compiler Design
Three address code In Compiler DesignThree address code In Compiler Design
Three address code In Compiler Design
Shine Raj
 
Undecidability.pptx
Undecidability.pptxUndecidability.pptx
Undecidability.pptx
PEzhumalai
 
Searching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureSearching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data Structure
Balwant Gorad
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
sandeep54552
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
Dhaval Kaneria
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
kalyanineve
 
Lecture 17 Iterative Deepening a star algorithm
Lecture 17 Iterative Deepening a star algorithmLecture 17 Iterative Deepening a star algorithm
Lecture 17 Iterative Deepening a star algorithm
Hema Kashyap
 
Intermediate code generation
Intermediate code generationIntermediate code generation
Intermediate code generation
Akshaya Arunan
 
Strings in C
Strings in CStrings in C
Strings in C
Kamal Acharya
 
Recurrence relation solutions
Recurrence relation solutionsRecurrence relation solutions
Recurrence relation solutions
subhashchandra197
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
Ganesh Solanke
 
Function
FunctionFunction
Function
yash patel
 
Heap management in Compiler Construction
Heap management in Compiler ConstructionHeap management in Compiler Construction
Heap management in Compiler Construction
Muhammad Haroon
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Dr Sukhpal Singh Gill
 
Spanning trees
Spanning treesSpanning trees
Spanning trees
Shareb Ismaeel
 
Heap sort
Heap sort Heap sort
Programming in c
Programming in cProgramming in c
Programming in c
indra Kishor
 
Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive
Raj Naik
 
Best,worst,average case .17581556 045
Best,worst,average case .17581556 045Best,worst,average case .17581556 045
Best,worst,average case .17581556 045
university of Gujrat, pakistan
 

Tendances (20)

Introduction to design and analysis of algorithm
Introduction to design and analysis of algorithmIntroduction to design and analysis of algorithm
Introduction to design and analysis of algorithm
 
Three address code In Compiler Design
Three address code In Compiler DesignThree address code In Compiler Design
Three address code In Compiler Design
 
Undecidability.pptx
Undecidability.pptxUndecidability.pptx
Undecidability.pptx
 
Searching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureSearching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data Structure
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
 
Lecture 17 Iterative Deepening a star algorithm
Lecture 17 Iterative Deepening a star algorithmLecture 17 Iterative Deepening a star algorithm
Lecture 17 Iterative Deepening a star algorithm
 
Intermediate code generation
Intermediate code generationIntermediate code generation
Intermediate code generation
 
Strings in C
Strings in CStrings in C
Strings in C
 
Recurrence relation solutions
Recurrence relation solutionsRecurrence relation solutions
Recurrence relation solutions
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
Function
FunctionFunction
Function
 
Heap management in Compiler Construction
Heap management in Compiler ConstructionHeap management in Compiler Construction
Heap management in Compiler Construction
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Spanning trees
Spanning treesSpanning trees
Spanning trees
 
Heap sort
Heap sort Heap sort
Heap sort
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive
 
Best,worst,average case .17581556 045
Best,worst,average case .17581556 045Best,worst,average case .17581556 045
Best,worst,average case .17581556 045
 

Similaire à RECURSION.pptx

01_intro-cpp.ppt
01_intro-cpp.ppt01_intro-cpp.ppt
01_intro-cpp.ppt
SWETHAABIRAMIM
 
01_intro-cpp.ppt
01_intro-cpp.ppt01_intro-cpp.ppt
01_intro-cpp.ppt
DrBashirMSaad
 
Realtime Analytics
Realtime AnalyticsRealtime Analytics
Realtime Analytics
eXascale Infolab
 
Recursion in Data Structure
Recursion in Data StructureRecursion in Data Structure
Recursion in Data Structure
khudabux1998
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational Engineering
Sri Harsha Pamu
 
An Introduction to Deep Learning
An Introduction to Deep LearningAn Introduction to Deep Learning
An Introduction to Deep Learning
milad abbasi
 
Introduction to Deep Learning
Introduction to Deep LearningIntroduction to Deep Learning
Introduction to Deep Learning
Mehrnaz Faraz
 
lecture1.ppt
lecture1.pptlecture1.ppt
lecture1.ppt
SagarDR5
 
C++ Notes PPT.ppt
C++ Notes PPT.pptC++ Notes PPT.ppt
C++ Notes PPT.ppt
Alpha474815
 
2.03.Asymptotic_analysis.pptx
2.03.Asymptotic_analysis.pptx2.03.Asymptotic_analysis.pptx
2.03.Asymptotic_analysis.pptx
ssuser1fb3df
 
VCE Unit 01 (1).pptx
VCE Unit 01 (1).pptxVCE Unit 01 (1).pptx
VCE Unit 01 (1).pptx
skilljiolms
 
complexity analysis.pdf
complexity analysis.pdfcomplexity analysis.pdf
complexity analysis.pdf
pasinduneshan
 
Algorithms
Algorithms Algorithms
Algorithms
yashodhaHR2
 
Design & Analysis of Algorithm course .pptx
Design & Analysis of Algorithm course .pptxDesign & Analysis of Algorithm course .pptx
Design & Analysis of Algorithm course .pptx
JeevaMCSEKIOT
 
Unsupervised Learning: Clustering
Unsupervised Learning: Clustering Unsupervised Learning: Clustering
Unsupervised Learning: Clustering
Experfy
 
Parallel Computing 2007: Bring your own parallel application
Parallel Computing 2007: Bring your own parallel applicationParallel Computing 2007: Bring your own parallel application
Parallel Computing 2007: Bring your own parallel application
Geoffrey Fox
 
Lec1.pptx
Lec1.pptxLec1.pptx
data-stream-processing-SEEP.pptx
data-stream-processing-SEEP.pptxdata-stream-processing-SEEP.pptx
data-stream-processing-SEEP.pptx
AhmadTawfigAlRadaide
 
Analysis of Algorithms
Analysis of AlgorithmsAnalysis of Algorithms
Analysis of Algorithms
Amna Saeed
 
Daa
DaaDaa

Similaire à RECURSION.pptx (20)

01_intro-cpp.ppt
01_intro-cpp.ppt01_intro-cpp.ppt
01_intro-cpp.ppt
 
01_intro-cpp.ppt
01_intro-cpp.ppt01_intro-cpp.ppt
01_intro-cpp.ppt
 
Realtime Analytics
Realtime AnalyticsRealtime Analytics
Realtime Analytics
 
Recursion in Data Structure
Recursion in Data StructureRecursion in Data Structure
Recursion in Data Structure
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational Engineering
 
An Introduction to Deep Learning
An Introduction to Deep LearningAn Introduction to Deep Learning
An Introduction to Deep Learning
 
Introduction to Deep Learning
Introduction to Deep LearningIntroduction to Deep Learning
Introduction to Deep Learning
 
lecture1.ppt
lecture1.pptlecture1.ppt
lecture1.ppt
 
C++ Notes PPT.ppt
C++ Notes PPT.pptC++ Notes PPT.ppt
C++ Notes PPT.ppt
 
2.03.Asymptotic_analysis.pptx
2.03.Asymptotic_analysis.pptx2.03.Asymptotic_analysis.pptx
2.03.Asymptotic_analysis.pptx
 
VCE Unit 01 (1).pptx
VCE Unit 01 (1).pptxVCE Unit 01 (1).pptx
VCE Unit 01 (1).pptx
 
complexity analysis.pdf
complexity analysis.pdfcomplexity analysis.pdf
complexity analysis.pdf
 
Algorithms
Algorithms Algorithms
Algorithms
 
Design & Analysis of Algorithm course .pptx
Design & Analysis of Algorithm course .pptxDesign & Analysis of Algorithm course .pptx
Design & Analysis of Algorithm course .pptx
 
Unsupervised Learning: Clustering
Unsupervised Learning: Clustering Unsupervised Learning: Clustering
Unsupervised Learning: Clustering
 
Parallel Computing 2007: Bring your own parallel application
Parallel Computing 2007: Bring your own parallel applicationParallel Computing 2007: Bring your own parallel application
Parallel Computing 2007: Bring your own parallel application
 
Lec1.pptx
Lec1.pptxLec1.pptx
Lec1.pptx
 
data-stream-processing-SEEP.pptx
data-stream-processing-SEEP.pptxdata-stream-processing-SEEP.pptx
data-stream-processing-SEEP.pptx
 
Analysis of Algorithms
Analysis of AlgorithmsAnalysis of Algorithms
Analysis of Algorithms
 
Daa
DaaDaa
Daa
 

Dernier

NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
TechSoup
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
ssuser13ffe4
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
S. Raj Kumar
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Denish Jangid
 
IGCSE Biology Chapter 14- Reproduction in Plants.pdf
IGCSE Biology Chapter 14- Reproduction in Plants.pdfIGCSE Biology Chapter 14- Reproduction in Plants.pdf
IGCSE Biology Chapter 14- Reproduction in Plants.pdf
Amin Marwan
 
Solutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptxSolutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptx
spdendr
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
Nguyen Thanh Tu Collection
 
Constructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective CommunicationConstructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective Communication
Chevonnese Chevers Whyte, MBA, B.Sc.
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 

Dernier (20)

NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
 
IGCSE Biology Chapter 14- Reproduction in Plants.pdf
IGCSE Biology Chapter 14- Reproduction in Plants.pdfIGCSE Biology Chapter 14- Reproduction in Plants.pdf
IGCSE Biology Chapter 14- Reproduction in Plants.pdf
 
Solutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptxSolutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptx
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
 
Constructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective CommunicationConstructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective Communication
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 

RECURSION.pptx

  • 2. Produced by Mapako M 2 Objectives • Learn about recursive definitions • Explore the base case and the general case of a recursive definition • Learn about recursive algorithm • Learn about recursive functions • Explore how to use recursive functions to implement recursive
  • 3. Data Structures Using C++ 3 Recursive Definitions • Recursion – Process of solving a problem by reducing it to smaller versions of itself – The recursive algorithm must have one or more base case(s), and the general solurion must eventually be reduced to a base case
  • 4. Recursive Definitions (cont’d.) • Direct solution – Right side of the equation contains no factorial notation • Recursive definition – A definition in which something is defined in terms of a smaller version of itself • Base case – Case for which the solution is obtained directly – The case for which the solution can be stated non- recursively Data Structures Using C++ 4
  • 5. Recursive Definitions (cont’d.) • General(Recursive) case – Case for which the solution is obtained indirectly using recursion – Case for which the solution is expressed in terms of the smaller version of itself • Recursive algorithm – A solution that is expressed in terms of smaller instances of itself and a base case – Finds problem solution by reducing problem to smaller versions of itself Data Structures Using C++ 5
  • 6. Data Structures Using C++ 6 Recursive Definitions (cont’d.) • Recursion insight gained from factorial problem – Every recursive definition must have one (or more) base cases – General case must eventually reduce to a base case – Base case stops recursion • Recursive function – Function that calls itself
  • 7. Recursive Definitions (cont’d.) • Recursive function notable comments – Recursive function has unlimited number of copies of itself (logically) – Every call to a recursive function has its own • Code, set of parameters, local variables – After completing a particular recursive call • Control goes back to calling environment (previous call) • Current (recursive) call must execute completely before control goes back to the previous call • Execution in previous call begins from point immediately following the recursive call Data Structures Using C++ 7
  • 8. Data Structures Using C++ 8 Recursive Definitions (cont’d.) • Direct and indirect recursion – Directly recursive function • Calls itself – Indirectly recursive function • Calls another function, eventually results in original function call • Requires same analysis as direct recursion • Base cases must be identified, appropriate solutions to them provided • Tracing can be tedious – Tail recursive function • Last statement executed: the recursive call
  • 9. Data Structures Using C++ 9 Recursive Definitions (cont’d.) • Infinite recursion – Occurs if every recursive call results in another recursive call – Executes forever (in theory) – Call requirements for recursive functions • System memory for local variables and formal parameters • Saving information for transfer back to right caller – Finite system memory leads to • Execution until system runs out of memory • Abnormal termination of infinite recursive function
  • 10. Data Structures Using C++ 10 Recursive Definitions (cont’d.) • Requirements to design a recursive function – Understand problem requirements – Determine limiting conditions – Identify base cases, providing direct solution to each base case – Identify general cases, providing solution to each general case in terms of smaller versions of itself
  • 11. Data Structures Using C++ 11 Factorial • Recursive function implementing the factorial function FIGURE 6-1 Execution of factorial
  • 12. Data Structures Using C++ 12 Fibonacci Number • Sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34 . . . • Given first two numbers (a1 and a2) – nth number an, n >= 3, of sequence given by: an = an-1 + an-2 • Recursive function: rFibNum – Determines desired Fibonacci number – Parameters: three numbers representing first two numbers of the Fibonacci sequence and a number n, the desired nth Fibonacci number – Returns the nth Fibonacci number in the sequence
  • 13. Data Structures Using C++ 13 Fibonacci Number (cont’d.) • Third Fibonacci number – Sum of first two Fibonacci numbers • Fourth Fibonacci number in a sequence – Sum of second and third Fibonacci numbers • Calculating fourth Fibonacci number – Add second Fibonacci number and third Fibonacci number
  • 14. Data Structures Using C++ 14 Fibonacci Number (cont’d.) • Recursive algorithm – Calculates nth Fibonacci number • a denotes first Fibonacci number • b denotes second Fibonacci number • n denotes nth Fibonacci number • a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, etc.
  • 15. Data Structures Using C++ 15 Fibonacci Number (cont’d.) • Recursive function implementing algorithm • Trace code execution
  • 16. Data Structures Using C++ 16 Fibonacci Number (cont’d.) FIGURE 6-7 Execution of rFibNum(2, 3, 4)
  • 17. Data Structures Using C++ 17 Tower of Hanoi • Object – Move 64 disks from first needle to third needle • Rules – Only one disk can be moved at a time – Removed disk must be placed on one of the needles – A larger disk cannot be placed on top of a smaller disk FIGURE 6-8 Tower of Hanoi problem with three disks
  • 18. Data Structures Using C++ 18 Tower of Hanoi (cont’d.) • Case: first needle contains only one disk – Move disk directly from needle 1 to needle 3 • Case: first needle contains only two disks – Move first disk from needle 1 to needle 2 – Move second disk from needle 1 to needle 3 – Move first disk from needle 2 to needle 3 • Case: first needle contains three disks
  • 19. Data Structures Using C++ 19 Tower of Hanoi (cont’d.) FIGURE 6-9 Solution to Tower of Hanoi problem with three disks
  • 20. Data Structures Using C++ 20 Tower of Hanoi (cont’d.) • Generalize problem to the case of 64 disks – Recursive algorithm in pseudocode
  • 21. Data Structures Using C++ 21 Tower of Hanoi (cont’d.) • Generalize problem to the case of 64 disks – Recursive algorithm in C++
  • 22. Data Structures Using C++ 22 Tower of Hanoi (cont’d.) • Analysis of Tower of Hanoi – Time necessary to move all 64 disks from needle 1 to needle 3 – Manually: roughly 5 x 1011 years • Universe is about 15 billion years old (1.5 x 1010) – Computer: 500 years • To generate 264 moves at the rate of 1 billion moves per second
  • 23. Data Structures Using C++ 23 Converting a Number from Decimal to Binary • Convert nonnegative integer in decimal format (base 10) into equivalent binary number (base 2) • Rightmost bit of x – Remainder of x after division by two • Recursive algorithm pseudocode – Binary(num) denotes binary representation of num
  • 24. Data Structures Using C++ 24 Converting a Number from Decimal to Binary (cont’d.) • Recursive function implementing algorithm
  • 25. Data Structures Using C++ 25 Converting a Number from Decimal to Binary (cont’d.) FIGURE 6-10 Execution of decToBin(13, 2)
  • 26. Multiply 2 numbers by addition int multiply (int a,int b) { if(b==0)//base case for recursion to stop return 0; else return a + multiply(a,b-1);//recursive case } Data Structures Using C++ 26 • Recursive function implementing algorithm
  • 27. Computing powers via linear recursion int calculatePower(int base, int powerRaised) { if (powerRaised != 1) return (base*calculatePower(base, powerRaised-1)); else return 1; } Data Structures Using C++ 27
  • 28. Reversing an array • Algorithm ReverseArray(A, i, j): Input: An array A and nonnegative integer indices i and j Output: The reversal of the elements in A starting at index i and ending at j if i < j then Swap A[i] and A[j] ReverseArray(A, i+1, j-1) return Data Structures Using C++ 28
  • 29. Data Structures Using C++ 29 Recursion or Iteration? • Dependent upon nature of the solution and efficiency • Efficiency – Recursion is less efficient in terms of time and space – Overhead of recursive function: execution time and memory usage • Given speed memory of today’s computers, we can depend more on how programmer envisions solution – Use of programmer’s time – Any program that can be written recursively can also be written iteratively – Recursion is simpler and more natural for programmer to write
  • 30. Advantages of recursion • Recursion is a must to use in some programming situations like display a list of files of the system cannot be solved without recursion • Recursion is very flexible in data structures like stacks, queues, linked list and quick sort • Using recursion the length of the program can be reduced. • It makes the code easier to read as it reflex our normal manner of thinking • It makes a function or a procedure easier to understand Data Structures Using C++ 30
  • 31. Disadvantages of recursion • May be slower than iteration • Use greater resources because of extra function calls • More difficult to understand in some algorithms. An algorithm that can be naturally expressed iteratively may not be easy to understand if expressed recursively. • There is no portable way to tell how deep recursion can go without causing trouble( how much ‘stack space’ the machine has) and there is no way to recover from deep recursion( a stack overflow) Data Structures Using C++ 31
  • 32. Data Structures Using C++ 32 Summary • Recursion – Solve problem by reducing it to smaller versions of itself • Recursive algorithms implemented using recursive functions – Direct, indirect, and infinite recursion • Many problems solved using recursive algorithms • Choosing between recursion and iteration – Nature of solution; efficiency requirements • Backtracking – Problem solving; iterative design technique