SlideShare a Scribd company logo
1 of 40
RECURSION
Recursion
1. A function, which calls itself either directly or indirectly
through another function.
2. A recursive function is called to solve a problem.
3. The function actually knows how to solve only the
simplest case(s), or so-called base case(s)
4. If the function is called with the base case it simply
returns the result or in some cases do nothing.
Recursion
5. If the function is called with a more complex
problem (A), the function divides the problem
into two conceptual pieces (B and C).
These two pieces are a piece that the function
knows how to do (B – a base case) and a piece
that the function does not know how to do (C).
The latter piece (C) must resemble the original
problem, but be a slightly simpler or slightly
smaller version of the original problem (A).
Recursion Guidelines
 The definition of a recursive method typically
includes an if-else statement.
 One branch represents a base case which can
be solved directly (without recursion).
 Another branch includes a recursive call to the
method, but with a “simpler” or “smaller” set of
arguments.
 Ultimately, a base case must be reached.
Rules of Recursion
 Bad use of recursion, causes a huge amount
of redundant work being performed, violating
a major rule of recursion.
Rules of Recursion:
1. Base Case: You must always have some
base cases, which can be solved without
recursion.
2. Making Progress: Recursive call must
always be to a case that make progress
toward a base case.
Infinite Recursion
 If the recursive invocation inside the method
does not use a “simpler” or “smaller”
parameter, a base case may never be
reached.
 Such a method continues to call itself forever
(or at least until the resources of the computer
are exhausted as a consequence of stack
overflow).
 This is called infinite recursion.
Tracing a Recursive Method
7
 Given: public static void countDown(int integer)
{ System.out.println(integer);
if (integer > 1)
countDown(integer - 1);
} // end countDown
The effect of method call countDown(3)
Tracing a Recursive Method
8
Tracing the recursive
call countDown(3)
Tracing a Recursive Method
9
The stack of activation records during the execution of a
call to countDown(3)… continued →
Tracing a Recursive Method
10
The stack of activation records during the execution of a
call to countDown(3)
Note: the recursive
method will use more
memory than an
iterative method due
to the stack of
activation records
Recursive Methods That Return a
Value
11
 Task: Compute the sum
1 + 2 + 3 + … + n for an integer n > 0
public static int sumOf(int n)
{ int sum;
if (n = = 1)
sum = 1; // base case
else
sum = sumOf(n - 1) + n; // recursive call
return sum;
} // end sumOf
Recursive Methods That Return a
Value
12
The stack of activation records
during the execution of a call to sumOf(3)
Recursion vs. Iteration
 Any recursive method can be rewritten
without using recursion.
 Typically, a loop is used in place of the
recursion.
 The resulting method is referred to as the
iterative version.
Recursion vs. Iteration, cont.
 A recursive version of a method typically
executes less efficiently than the
corresponding iterative version.
 This is because the computer must keep track
of the recursive calls and the suspended
computations.
 However, it can be much easier to write a
recursive method than it is to write a
corresponding iterative method.
Recursion
 Recursion can describe everyday examples
 Show everything in a folder and all it subfolders
 show everything in top folder
 show everything in each subfolder in the same manner
Recursive Methods That Return a
Value
 A recursive method can be a void method or
it can return a value.
 At least one branch inside the recursive
method can compute and return a value by
making a chain of recursive calls.
Method factorial()
public static int factorial(n) {
if (n == 0) {
return 1;
}
else {
return n * factorial(n-1);
}
}
Recursive invocation
int nfactorial = factorial(n);
main()
 A new activation record is created for every
method invocation
 Including recursive invocations
Recursive invocation
int nfactorial = factorial(n);
main()
return n * factorial(n-1);
n = 3
factorial()
 A new activation record is created for every
method invocation
 Including recursive invocations
Recursive invocation
int nfactorial = factorial(n);
main()
return n * factorial(n-1);
n = 3
factorial()
return n * factorial(n-1);
n = 2
factorial()
 A new activation record is created for every
method invocation
 Including recursive invocations
Recursive invocation
int nfactorial = factorial(n);
main()
return n * factorial(n-1);
n = 3
factorial()
return n * factorial(n-1);
n = 2
factorial()
return n * factorial(n-1);
n = 1
factorial()
 A new activation record is created for every
method invocation
 Including recursive invocations
Recursive invocation
int nfactorial = factorial(n);
main()
return n * factorial(n-1);
n = 3
factorial()
return n * factorial(n-1);
n = 2
factorial()
return n * factorial(n-1);
n = 1
factorial()
return 1;
n = 0
factorial()
 A new activation record is created for every
method invocation
 Including recursive invocations
Recursive invocation
int nfactorial = factorial(n);
main()
return n * factorial(n-1);
n = 3
factorial()
return n * factorial(n-1);
n = 2
factorial()
return n * factorial(n-1);
n = 1
factorial()
return 1;
n = 0
factorial()
 A new activation record is created for every
method invocation
 Including recursive invocations
Recursive invocation
int nfactorial = factorial(n);
main()
return n * factorial(n-1);
n = 3
factorial()
return n * factorial(n-1);
n = 2
factorial()
return n * 1;
n = 1
factorial()
return 1;
n = 0
factorial()
 A new activation record is created for every
method invocation
 Including recursive invocations
Recursive invocation
int nfactorial = factorial(n);
main()
return n * factorial(n-1);
n = 3
factorial()
return n * factorial(n-1);
n = 2
factorial()
return 1 * 1;
n = 1
factorial()
 A new activation record is created for every
method invocation
 Including recursive invocations
Recursive invocation
int nfactorial = factorial(n);
main()
return n * factorial(n-1);
n = 3
factorial()
return n * 1
n = 2
factorial()
return 1 * 1;
n = 1
factorial()
 A new activation record is created for every
method invocation
 Including recursive invocations
Recursive invocation
int nfactorial = factorial(n);
main()
return n * factorial(n-1);
n = 3
factorial()
return 2 * 1
n = 2
factorial()
 A new activation record is created for every
method invocation
 Including recursive invocations
Recursive invocation
int nfactorial = factorial(n);
main()
return n * 2;
n = 3
factorial()
return 2 * 1;
n = 2
factorial()
 A new activation record is created for every
method invocation
 Including recursive invocations
Recursive invocation
int nfactorial = factorial(n);
main()
return 3 * 2;
n = 3
factorial()
 A new activation record is created for every
method invocation
 Including recursive invocations
Recursive invocation
int nfactorial = 6;
main()
return 3 * 2;
n = 3
factorial()
 A new activation record is created for every
method invocation
 Including recursive invocations
Recursive invocation
int nfactorial = 6;
main()
 A new activation record is created for every
method invocation
 Including recursive invocations
Infinite recursion
 A common programming error when using
recursion is to not stop making recursive calls.
 The program will continue to recurse until
it runs out of memory.
 Be sure that your recursive calls are made with
simpler or smaller subproblems, and that your
algorithm has a base case that terminates the
recursion.
Fibonacci Series Code
33
public static int fib (int n) {
if (n <= 2)
return 1;
else
return fib(n-1) + fib(n-2);
}
This is straightforward, but an inefficient recursion
...
Efficiency of Recursion: Inefficient
Fibonacci
34
Efficient Fibonacci
35
 Strategy: keep track of:
 Current Fibonacci number
 Previous Fibonacci number
Efficient Fibonacci: Code
36
public static int fibStart (int n) {
return fibo(1, 1, n);
}
private static int fibo (
int curr, int prev, int n) {
if (n <= 1)
return curr;
else
return fibo(curr+prev, curr, n-1);
}
Efficient Fibonacci: A Trace
37
Recursion Advantages
 Expressive Power
 Recursive code is typically much shorter than
iterative.
 More appropriate for certain problems.
 Intuitive programming from mathematic
definitions.
Recursion Disadvantages
 Usually slower due to call stack overhead.
 Faulty Programs are very difficult to debug.
 Difficult to prove a recursive algorithm is
correct
End

More Related Content

Similar to Recursion.ppt

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
 
(Recursion)ads
(Recursion)ads(Recursion)ads
(Recursion)adsRavi Rao
 
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structurecogaxor346
 
2022-9-recursive-1.pptx
2022-9-recursive-1.pptx2022-9-recursive-1.pptx
2022-9-recursive-1.pptxRayLee547290
 
Recursion - Algorithms and Data Structures
Recursion - Algorithms and Data StructuresRecursion - Algorithms and Data Structures
Recursion - Algorithms and Data StructuresPriyanka Rana
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdfjamvantsolanki
 
lecture 10 Recursive Function and Macros.ppt
lecture 10 Recursive Function and Macros.pptlecture 10 Recursive Function and Macros.ppt
lecture 10 Recursive Function and Macros.pptAbhishekkumarsingh630054
 
Recursion and looping
Recursion and loopingRecursion and looping
Recursion and loopingxcoolanurag
 
Recursion & its Application in C Language.
Recursion & its Application in C Language.Recursion & its Application in C Language.
Recursion & its Application in C Language.muhammadali405665
 

Similar to Recursion.ppt (20)

Lecture 12 - Recursion
Lecture 12 - Recursion Lecture 12 - Recursion
Lecture 12 - Recursion
 
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
 
(Recursion)ads
(Recursion)ads(Recursion)ads
(Recursion)ads
 
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structure
 
2022-9-recursive-1.pptx
2022-9-recursive-1.pptx2022-9-recursive-1.pptx
2022-9-recursive-1.pptx
 
Recursion.pdf
Recursion.pdfRecursion.pdf
Recursion.pdf
 
Recursion in c++
Recursion in c++Recursion in c++
Recursion in c++
 
Recursion - Algorithms and Data Structures
Recursion - Algorithms and Data StructuresRecursion - Algorithms and Data Structures
Recursion - Algorithms and Data Structures
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
 
14. Recursion.pdf
14. Recursion.pdf14. Recursion.pdf
14. Recursion.pdf
 
Cis068 08
Cis068 08Cis068 08
Cis068 08
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
 
3 recursion
3 recursion3 recursion
3 recursion
 
3-Recursion.ppt
3-Recursion.ppt3-Recursion.ppt
3-Recursion.ppt
 
recursion.ppt
recursion.pptrecursion.ppt
recursion.ppt
 
lecture 10 Recursive Function and Macros.ppt
lecture 10 Recursive Function and Macros.pptlecture 10 Recursive Function and Macros.ppt
lecture 10 Recursive Function and Macros.ppt
 
Recursion and looping
Recursion and loopingRecursion and looping
Recursion and looping
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 
functions
functionsfunctions
functions
 
Recursion & its Application in C Language.
Recursion & its Application in C Language.Recursion & its Application in C Language.
Recursion & its Application in C Language.
 

More from TalhaHussain58

Software Development life cycle
Software Development life cycle Software Development life cycle
Software Development life cycle TalhaHussain58
 
Communication skills Presentation.pptx
Communication skills Presentation.pptxCommunication skills Presentation.pptx
Communication skills Presentation.pptxTalhaHussain58
 
computer-mouse-sir-tariq.pptx
computer-mouse-sir-tariq.pptxcomputer-mouse-sir-tariq.pptx
computer-mouse-sir-tariq.pptxTalhaHussain58
 
Communication Skills.pptx
 Communication Skills.pptx Communication Skills.pptx
Communication Skills.pptxTalhaHussain58
 
Introduction to Communication Skills.pptx
Introduction to Communication Skills.pptxIntroduction to Communication Skills.pptx
Introduction to Communication Skills.pptxTalhaHussain58
 

More from TalhaHussain58 (9)

Software Development life cycle
Software Development life cycle Software Development life cycle
Software Development life cycle
 
Process Model.pptx
Process Model.pptxProcess Model.pptx
Process Model.pptx
 
Communication skills Presentation.pptx
Communication skills Presentation.pptxCommunication skills Presentation.pptx
Communication skills Presentation.pptx
 
computer-mouse-sir-tariq.pptx
computer-mouse-sir-tariq.pptxcomputer-mouse-sir-tariq.pptx
computer-mouse-sir-tariq.pptx
 
Communication Skills.pptx
 Communication Skills.pptx Communication Skills.pptx
Communication Skills.pptx
 
Laser Printer.pptx
Laser Printer.pptxLaser Printer.pptx
Laser Printer.pptx
 
lcd presentation
lcd presentation lcd presentation
lcd presentation
 
mouse Presentation
mouse Presentation mouse Presentation
mouse Presentation
 
Introduction to Communication Skills.pptx
Introduction to Communication Skills.pptxIntroduction to Communication Skills.pptx
Introduction to Communication Skills.pptx
 

Recently uploaded

Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoordharasingh5698
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfRagavanV2
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 

Recently uploaded (20)

Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 

Recursion.ppt

  • 2. Recursion 1. A function, which calls itself either directly or indirectly through another function. 2. A recursive function is called to solve a problem. 3. The function actually knows how to solve only the simplest case(s), or so-called base case(s) 4. If the function is called with the base case it simply returns the result or in some cases do nothing.
  • 3. Recursion 5. If the function is called with a more complex problem (A), the function divides the problem into two conceptual pieces (B and C). These two pieces are a piece that the function knows how to do (B – a base case) and a piece that the function does not know how to do (C). The latter piece (C) must resemble the original problem, but be a slightly simpler or slightly smaller version of the original problem (A).
  • 4. Recursion Guidelines  The definition of a recursive method typically includes an if-else statement.  One branch represents a base case which can be solved directly (without recursion).  Another branch includes a recursive call to the method, but with a “simpler” or “smaller” set of arguments.  Ultimately, a base case must be reached.
  • 5. Rules of Recursion  Bad use of recursion, causes a huge amount of redundant work being performed, violating a major rule of recursion. Rules of Recursion: 1. Base Case: You must always have some base cases, which can be solved without recursion. 2. Making Progress: Recursive call must always be to a case that make progress toward a base case.
  • 6. Infinite Recursion  If the recursive invocation inside the method does not use a “simpler” or “smaller” parameter, a base case may never be reached.  Such a method continues to call itself forever (or at least until the resources of the computer are exhausted as a consequence of stack overflow).  This is called infinite recursion.
  • 7. Tracing a Recursive Method 7  Given: public static void countDown(int integer) { System.out.println(integer); if (integer > 1) countDown(integer - 1); } // end countDown The effect of method call countDown(3)
  • 8. Tracing a Recursive Method 8 Tracing the recursive call countDown(3)
  • 9. Tracing a Recursive Method 9 The stack of activation records during the execution of a call to countDown(3)… continued →
  • 10. Tracing a Recursive Method 10 The stack of activation records during the execution of a call to countDown(3) Note: the recursive method will use more memory than an iterative method due to the stack of activation records
  • 11. Recursive Methods That Return a Value 11  Task: Compute the sum 1 + 2 + 3 + … + n for an integer n > 0 public static int sumOf(int n) { int sum; if (n = = 1) sum = 1; // base case else sum = sumOf(n - 1) + n; // recursive call return sum; } // end sumOf
  • 12. Recursive Methods That Return a Value 12 The stack of activation records during the execution of a call to sumOf(3)
  • 13. Recursion vs. Iteration  Any recursive method can be rewritten without using recursion.  Typically, a loop is used in place of the recursion.  The resulting method is referred to as the iterative version.
  • 14. Recursion vs. Iteration, cont.  A recursive version of a method typically executes less efficiently than the corresponding iterative version.  This is because the computer must keep track of the recursive calls and the suspended computations.  However, it can be much easier to write a recursive method than it is to write a corresponding iterative method.
  • 15. Recursion  Recursion can describe everyday examples  Show everything in a folder and all it subfolders  show everything in top folder  show everything in each subfolder in the same manner
  • 16. Recursive Methods That Return a Value  A recursive method can be a void method or it can return a value.  At least one branch inside the recursive method can compute and return a value by making a chain of recursive calls.
  • 17. Method factorial() public static int factorial(n) { if (n == 0) { return 1; } else { return n * factorial(n-1); } }
  • 18. Recursive invocation int nfactorial = factorial(n); main()  A new activation record is created for every method invocation  Including recursive invocations
  • 19. Recursive invocation int nfactorial = factorial(n); main() return n * factorial(n-1); n = 3 factorial()  A new activation record is created for every method invocation  Including recursive invocations
  • 20. Recursive invocation int nfactorial = factorial(n); main() return n * factorial(n-1); n = 3 factorial() return n * factorial(n-1); n = 2 factorial()  A new activation record is created for every method invocation  Including recursive invocations
  • 21. Recursive invocation int nfactorial = factorial(n); main() return n * factorial(n-1); n = 3 factorial() return n * factorial(n-1); n = 2 factorial() return n * factorial(n-1); n = 1 factorial()  A new activation record is created for every method invocation  Including recursive invocations
  • 22. Recursive invocation int nfactorial = factorial(n); main() return n * factorial(n-1); n = 3 factorial() return n * factorial(n-1); n = 2 factorial() return n * factorial(n-1); n = 1 factorial() return 1; n = 0 factorial()  A new activation record is created for every method invocation  Including recursive invocations
  • 23. Recursive invocation int nfactorial = factorial(n); main() return n * factorial(n-1); n = 3 factorial() return n * factorial(n-1); n = 2 factorial() return n * factorial(n-1); n = 1 factorial() return 1; n = 0 factorial()  A new activation record is created for every method invocation  Including recursive invocations
  • 24. Recursive invocation int nfactorial = factorial(n); main() return n * factorial(n-1); n = 3 factorial() return n * factorial(n-1); n = 2 factorial() return n * 1; n = 1 factorial() return 1; n = 0 factorial()  A new activation record is created for every method invocation  Including recursive invocations
  • 25. Recursive invocation int nfactorial = factorial(n); main() return n * factorial(n-1); n = 3 factorial() return n * factorial(n-1); n = 2 factorial() return 1 * 1; n = 1 factorial()  A new activation record is created for every method invocation  Including recursive invocations
  • 26. Recursive invocation int nfactorial = factorial(n); main() return n * factorial(n-1); n = 3 factorial() return n * 1 n = 2 factorial() return 1 * 1; n = 1 factorial()  A new activation record is created for every method invocation  Including recursive invocations
  • 27. Recursive invocation int nfactorial = factorial(n); main() return n * factorial(n-1); n = 3 factorial() return 2 * 1 n = 2 factorial()  A new activation record is created for every method invocation  Including recursive invocations
  • 28. Recursive invocation int nfactorial = factorial(n); main() return n * 2; n = 3 factorial() return 2 * 1; n = 2 factorial()  A new activation record is created for every method invocation  Including recursive invocations
  • 29. Recursive invocation int nfactorial = factorial(n); main() return 3 * 2; n = 3 factorial()  A new activation record is created for every method invocation  Including recursive invocations
  • 30. Recursive invocation int nfactorial = 6; main() return 3 * 2; n = 3 factorial()  A new activation record is created for every method invocation  Including recursive invocations
  • 31. Recursive invocation int nfactorial = 6; main()  A new activation record is created for every method invocation  Including recursive invocations
  • 32. Infinite recursion  A common programming error when using recursion is to not stop making recursive calls.  The program will continue to recurse until it runs out of memory.  Be sure that your recursive calls are made with simpler or smaller subproblems, and that your algorithm has a base case that terminates the recursion.
  • 33. Fibonacci Series Code 33 public static int fib (int n) { if (n <= 2) return 1; else return fib(n-1) + fib(n-2); } This is straightforward, but an inefficient recursion ...
  • 34. Efficiency of Recursion: Inefficient Fibonacci 34
  • 35. Efficient Fibonacci 35  Strategy: keep track of:  Current Fibonacci number  Previous Fibonacci number
  • 36. Efficient Fibonacci: Code 36 public static int fibStart (int n) { return fibo(1, 1, n); } private static int fibo ( int curr, int prev, int n) { if (n <= 1) return curr; else return fibo(curr+prev, curr, n-1); }
  • 38. Recursion Advantages  Expressive Power  Recursive code is typically much shorter than iterative.  More appropriate for certain problems.  Intuitive programming from mathematic definitions.
  • 39. Recursion Disadvantages  Usually slower due to call stack overhead.  Faulty Programs are very difficult to debug.  Difficult to prove a recursive algorithm is correct
  • 40. End