SlideShare a Scribd company logo
1 of 32
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

More Related Content

What's hot

Booth’s algorithm.(a014& a015)
Booth’s algorithm.(a014& a015)Booth’s algorithm.(a014& a015)
Booth’s algorithm.(a014& a015)
Piyush Rochwani
 
Fonctions formules excel
Fonctions formules excelFonctions formules excel
Fonctions formules excel
Carlitza
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysis
sumitbardhan
 

What's hot (20)

Credit Card Systems
Credit Card SystemsCredit Card Systems
Credit Card Systems
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Ejercicios RSA
Ejercicios RSAEjercicios RSA
Ejercicios RSA
 
Recursion
RecursionRecursion
Recursion
 
File operations in c
File operations in cFile operations in c
File operations in c
 
Booth’s algorithm.(a014& a015)
Booth’s algorithm.(a014& a015)Booth’s algorithm.(a014& a015)
Booth’s algorithm.(a014& a015)
 
Algorithmique et programmation en Pascal (résumé)
Algorithmique et programmation en Pascal (résumé)Algorithmique et programmation en Pascal (résumé)
Algorithmique et programmation en Pascal (résumé)
 
Programming language
Programming languageProgramming language
Programming language
 
Reseaux+info+bac+lettres
Reseaux+info+bac+lettresReseaux+info+bac+lettres
Reseaux+info+bac+lettres
 
Knuth morris pratt string matching algo
Knuth morris pratt string matching algoKnuth morris pratt string matching algo
Knuth morris pratt string matching algo
 
Np cooks theorem
Np cooks theoremNp cooks theorem
Np cooks theorem
 
Unit 3 graph chapter6
Unit 3  graph chapter6Unit 3  graph chapter6
Unit 3 graph chapter6
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Rough K Means - Numerical Example
Rough K Means - Numerical ExampleRough K Means - Numerical Example
Rough K Means - Numerical Example
 
Fonctions formules excel
Fonctions formules excelFonctions formules excel
Fonctions formules excel
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysis
 
2-Archivos.ppt
2-Archivos.ppt2-Archivos.ppt
2-Archivos.ppt
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Recurrences
RecurrencesRecurrences
Recurrences
 
Theory of Computation Unit 3
Theory of Computation Unit 3Theory of Computation Unit 3
Theory of Computation Unit 3
 

Similar to RECURSION.pptx

Similar to 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
 
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
 
C++ Notes PPT.ppt
C++ Notes PPT.pptC++ Notes PPT.ppt
C++ Notes PPT.ppt
 
lecture1.ppt
lecture1.pptlecture1.ppt
lecture1.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
 
Design & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture NotesDesign & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture Notes
 

Recently uploaded

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 

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