SlideShare a Scribd company logo
Recursion
Recursion
• In mathematics, we often say that a recursive solution is a solution such that f(xk) depends on
some of f(xk-1), f(xk-2),...f(x1), and f(x0)
• A usable recursive solution usually has the following characteristics
• –A base case. This is one which is easily calculated. It also prevents infinite loops!
• –A recursive case. This is the case in which the function “calls itself” in order to reduce the
calculations to the base case.
Simple problems solved recursively
• In math class we learned that 1+2+3+...+n = n*(n+1)/2
• For example, 1+2+...+10 = 10*11/2 = 55
• It is also easy to find the sum iteratively by an O(n) algorithm
int sum=0;
for i = 1 to n
sum=sum + i
• We can also solve this problem by recursion.
• Recursion to find 1 + 2 + + … + n
public sum(n)
if n == 1, sum =1
if n > 1, sum = n +sum(n-1)
Identify the base case
Identify the recursive case
• Example: sum(5) = 5 + sum(4)
= 5+4+sum(3) =9 +sum(3)
=9 +3+sum(2)
= 12 = 12 = 14 = 14
+sum(2)= +2+sum(1)
• On the next slide, we implement the recursive function in Java
• Recursive sum used to find the sum to n for n = 1, 2, ..., 10
• Note there is NO reason to compute the sums this way. This example is purely for illustration of
recursion.
n!
• From math class, we know that n! = n*(n-1)*(n-2)*...*3*2*1
3! = 3*2*1 = 6
5!= 5*4*3 *2 *1
• It is easy to compute n! iteratively
int prod = 1;
for i=2 to n
prod = prod * i
Recursive n!
• We easily observe that there is a recursive definition of n!
n! = n*(n-1) !
• For example 4 ! = 4*3*2*1 = 4*(3*2*1) = 4 * 3!
• This prompts the following function
int nfact (int n)
if n == 0 or n ==1
return 1
else
return n * nfact (n-1)
Fibonacci Numbers
• The Fibonacci number sequence:
1, 1, 2, 3, 5, 8, 13, ....
• The first two elements of the sequence are both 1
• Subsequent elements are formed by adding the two before it.
• Recursive Fibonacci
fib (n)
if (n==1 or n==0)
return 1;
else
return fib (n-1) + fib (n-2)
Recursive & Iterative Fibonacci
Notice how short and compact the recursive
version is.
Remarks about recursion
• In general
• A recursive solution is simpler to code than an iterative solution
• Some problems are so difficult that recursion may be the best solution
• Iterative solutions are often faster than recursive solutions
Recursive search
• It is very simple to write an iterative search to determine if a given value (toFind) is in an array
for i = 0 to the array length -1
if array[i] = to_find
return true
End i loop
Return false
• When we do it recursively
• If the array has length 1, we return true if the single element and toFind are the same
• If not
• we check the first element and return true if it and toFind are equal
• Otherwise, we repeat the search on the remainder of the array
Recursion

More Related Content

What's hot

Discreate time system and z transform
Discreate time system and z transformDiscreate time system and z transform
Discreate time system and z transform
VIKAS KUMAR MANJHI
 
レポート深層学習前編
レポート深層学習前編レポート深層学習前編
レポート深層学習前編
ssuser9d95b3
 
Z transform
 Z transform Z transform
Z transform
hemakankshini
 
21 2 ztransform
21 2 ztransform21 2 ztransform
21 2 ztransform
Mahyar Alzobaidy
 
Hyperbolictangent exercise
Hyperbolictangent exerciseHyperbolictangent exercise
Hyperbolictangent exercise
ritahani
 
Advance logic
Advance logicAdvance logic
Advance logic
Mazharul Islam
 
PowerPoint Presentation
PowerPoint PresentationPowerPoint Presentation
PowerPoint Presentation
butest
 
21 5 ztransform
21 5 ztransform21 5 ztransform
21 5 ztransform
Mahyar Alzobaidy
 
Applications of Z transform
Applications of Z transformApplications of Z transform
Applications of Z transform
AakankshaR
 

What's hot (9)

Discreate time system and z transform
Discreate time system and z transformDiscreate time system and z transform
Discreate time system and z transform
 
レポート深層学習前編
レポート深層学習前編レポート深層学習前編
レポート深層学習前編
 
Z transform
 Z transform Z transform
Z transform
 
21 2 ztransform
21 2 ztransform21 2 ztransform
21 2 ztransform
 
Hyperbolictangent exercise
Hyperbolictangent exerciseHyperbolictangent exercise
Hyperbolictangent exercise
 
Advance logic
Advance logicAdvance logic
Advance logic
 
PowerPoint Presentation
PowerPoint PresentationPowerPoint Presentation
PowerPoint Presentation
 
21 5 ztransform
21 5 ztransform21 5 ztransform
21 5 ztransform
 
Applications of Z transform
Applications of Z transformApplications of Z transform
Applications of Z transform
 

Similar to Recursion

Recursion.pdf
Recursion.pdfRecursion.pdf
Recursion.pdf
Flavia Tembo Kambale
 
Recursion
RecursionRecursion
6-Python-Recursion.pdf
6-Python-Recursion.pdf6-Python-Recursion.pdf
6-Python-Recursion.pdf
AshishPalandurkar2
 
lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptx
Lizhen Shi
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 
Dynamic programing
Dynamic programingDynamic programing
Dynamic programing
AniketSingh609353
 
Copy of y16 02-2119divide-and-conquer
Copy of y16 02-2119divide-and-conquerCopy of y16 02-2119divide-and-conquer
Copy of y16 02-2119divide-and-conquer
Joepang2015
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
Gopi Saiteja
 
Sec4
Sec4Sec4
DS & Algo 2 - Recursion
DS & Algo 2 - RecursionDS & Algo 2 - Recursion
DS & Algo 2 - Recursion
Mohammad Imam Hossain
 
1 chapter1 introduction
1 chapter1 introduction1 chapter1 introduction
1 chapter1 introduction
SSE_AndyLi
 
Dynamic programming Basics
Dynamic programming BasicsDynamic programming Basics
Dynamic programming Basics
Kvishnu Dahatonde
 
Recursion
RecursionRecursion
Recursion
Jesmin Akhter
 
Lecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrencesLecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrences
jayavignesh86
 
RecursionWeek8.ppt
RecursionWeek8.pptRecursionWeek8.ppt
RecursionWeek8.ppt
kawtherabass1
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103
Sure Interview
 
Lecture 3 complexity
Lecture 3 complexityLecture 3 complexity
Lecture 3 complexity
Madhu Niket
 
Recursion
RecursionRecursion
Recursion
Abdur Rehman
 
Ch01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonCh01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluiton
shin
 
Skiena algorithm 2007 lecture16 introduction to dynamic programming
Skiena algorithm 2007 lecture16 introduction to dynamic programmingSkiena algorithm 2007 lecture16 introduction to dynamic programming
Skiena algorithm 2007 lecture16 introduction to dynamic programming
zukun
 

Similar to Recursion (20)

Recursion.pdf
Recursion.pdfRecursion.pdf
Recursion.pdf
 
Recursion
RecursionRecursion
Recursion
 
6-Python-Recursion.pdf
6-Python-Recursion.pdf6-Python-Recursion.pdf
6-Python-Recursion.pdf
 
lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptx
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 
Dynamic programing
Dynamic programingDynamic programing
Dynamic programing
 
Copy of y16 02-2119divide-and-conquer
Copy of y16 02-2119divide-and-conquerCopy of y16 02-2119divide-and-conquer
Copy of y16 02-2119divide-and-conquer
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Sec4
Sec4Sec4
Sec4
 
DS & Algo 2 - Recursion
DS & Algo 2 - RecursionDS & Algo 2 - Recursion
DS & Algo 2 - Recursion
 
1 chapter1 introduction
1 chapter1 introduction1 chapter1 introduction
1 chapter1 introduction
 
Dynamic programming Basics
Dynamic programming BasicsDynamic programming Basics
Dynamic programming Basics
 
Recursion
RecursionRecursion
Recursion
 
Lecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrencesLecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrences
 
RecursionWeek8.ppt
RecursionWeek8.pptRecursionWeek8.ppt
RecursionWeek8.ppt
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103
 
Lecture 3 complexity
Lecture 3 complexityLecture 3 complexity
Lecture 3 complexity
 
Recursion
RecursionRecursion
Recursion
 
Ch01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonCh01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluiton
 
Skiena algorithm 2007 lecture16 introduction to dynamic programming
Skiena algorithm 2007 lecture16 introduction to dynamic programmingSkiena algorithm 2007 lecture16 introduction to dynamic programming
Skiena algorithm 2007 lecture16 introduction to dynamic programming
 

More from SAGARDAVE29

Graphical User Interface (GUI)
Graphical User Interface (GUI)Graphical User Interface (GUI)
Graphical User Interface (GUI)
SAGARDAVE29
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
SAGARDAVE29
 
Exception Handling
Exception HandlingException Handling
Exception Handling
SAGARDAVE29
 
JAVA Multithreading
JAVA MultithreadingJAVA Multithreading
JAVA Multithreading
SAGARDAVE29
 
Stack & Queue
Stack & QueueStack & Queue
Stack & Queue
SAGARDAVE29
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
SAGARDAVE29
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
SAGARDAVE29
 
Exception handling
Exception handlingException handling
Exception handling
SAGARDAVE29
 
More oop in java
More oop in javaMore oop in java
More oop in java
SAGARDAVE29
 
Coding Style & Tips for JAVA
Coding Style & Tips for JAVACoding Style & Tips for JAVA
Coding Style & Tips for JAVA
SAGARDAVE29
 
Some Important Methods in JAVA
Some Important Methods in JAVASome Important Methods in JAVA
Some Important Methods in JAVA
SAGARDAVE29
 
Inheritance & Polymorphism
Inheritance & PolymorphismInheritance & Polymorphism
Inheritance & Polymorphism
SAGARDAVE29
 

More from SAGARDAVE29 (12)

Graphical User Interface (GUI)
Graphical User Interface (GUI)Graphical User Interface (GUI)
Graphical User Interface (GUI)
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
JAVA Multithreading
JAVA MultithreadingJAVA Multithreading
JAVA Multithreading
 
Stack & Queue
Stack & QueueStack & Queue
Stack & Queue
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Exception handling
Exception handlingException handling
Exception handling
 
More oop in java
More oop in javaMore oop in java
More oop in java
 
Coding Style & Tips for JAVA
Coding Style & Tips for JAVACoding Style & Tips for JAVA
Coding Style & Tips for JAVA
 
Some Important Methods in JAVA
Some Important Methods in JAVASome Important Methods in JAVA
Some Important Methods in JAVA
 
Inheritance & Polymorphism
Inheritance & PolymorphismInheritance & Polymorphism
Inheritance & Polymorphism
 

Recently uploaded

Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
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
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
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
 
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
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 

Recently uploaded (20)

Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
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
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
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
 
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
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 

Recursion

  • 2. Recursion • In mathematics, we often say that a recursive solution is a solution such that f(xk) depends on some of f(xk-1), f(xk-2),...f(x1), and f(x0) • A usable recursive solution usually has the following characteristics • –A base case. This is one which is easily calculated. It also prevents infinite loops! • –A recursive case. This is the case in which the function “calls itself” in order to reduce the calculations to the base case.
  • 3. Simple problems solved recursively • In math class we learned that 1+2+3+...+n = n*(n+1)/2 • For example, 1+2+...+10 = 10*11/2 = 55 • It is also easy to find the sum iteratively by an O(n) algorithm int sum=0; for i = 1 to n sum=sum + i • We can also solve this problem by recursion.
  • 4. • Recursion to find 1 + 2 + + … + n public sum(n) if n == 1, sum =1 if n > 1, sum = n +sum(n-1) Identify the base case Identify the recursive case • Example: sum(5) = 5 + sum(4) = 5+4+sum(3) =9 +sum(3) =9 +3+sum(2) = 12 = 12 = 14 = 14 +sum(2)= +2+sum(1) • On the next slide, we implement the recursive function in Java
  • 5. • Recursive sum used to find the sum to n for n = 1, 2, ..., 10 • Note there is NO reason to compute the sums this way. This example is purely for illustration of recursion.
  • 6. n! • From math class, we know that n! = n*(n-1)*(n-2)*...*3*2*1 3! = 3*2*1 = 6 5!= 5*4*3 *2 *1 • It is easy to compute n! iteratively int prod = 1; for i=2 to n prod = prod * i
  • 7. Recursive n! • We easily observe that there is a recursive definition of n! n! = n*(n-1) ! • For example 4 ! = 4*3*2*1 = 4*(3*2*1) = 4 * 3! • This prompts the following function int nfact (int n) if n == 0 or n ==1 return 1 else return n * nfact (n-1)
  • 8. Fibonacci Numbers • The Fibonacci number sequence: 1, 1, 2, 3, 5, 8, 13, .... • The first two elements of the sequence are both 1 • Subsequent elements are formed by adding the two before it. • Recursive Fibonacci fib (n) if (n==1 or n==0) return 1; else return fib (n-1) + fib (n-2)
  • 9. Recursive & Iterative Fibonacci Notice how short and compact the recursive version is.
  • 10. Remarks about recursion • In general • A recursive solution is simpler to code than an iterative solution • Some problems are so difficult that recursion may be the best solution • Iterative solutions are often faster than recursive solutions
  • 11. Recursive search • It is very simple to write an iterative search to determine if a given value (toFind) is in an array for i = 0 to the array length -1 if array[i] = to_find return true End i loop Return false • When we do it recursively • If the array has length 1, we return true if the single element and toFind are the same • If not • we check the first element and return true if it and toFind are equal • Otherwise, we repeat the search on the remainder of the array