SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Welcome to CIS 068 ! Lesson 8:  Stacks and Recursion
Overview ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Stacks: Introduction ,[object Object],Plate Dispenser PEZ ® Dispenser
Stack: Properties ,[object Object],[object Object],1 2 3 4 5 6 1 2 3 4 5 6
Stacks: Properties ,[object Object],[object Object],[object Object]
Stacks: Definition ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Stacks ,[object Object],[object Object],[object Object],[object Object],[object Object]
A look into the JVM ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
A look into the JVM ,[object Object],[object Object],[object Object],[object Object]
A look into the JVM ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],a = 3 a = 3 b Return to LINE 3 b = 5 c = 15
A look into the JVM ,[object Object],[object Object],[object Object],a = 3 a = 3 b Return to LINE 3 b = 5 c = 15  15  a = 3 b Return to LINE 3 a = 3 b c = 15  Return to LINE 3 Temporary storage Clear Stack
A look into the JVM A look into the JVM 1  public static void main(String args[ ]){ 2 int a = 3; 3 int b = timesFive(a); 4 System.out.println(b+““); 5 } a = 3 b c = 15  Temporary storage a = 3 b = 15
A look into the JVM A look into the JVM 1  public static void main(String args[ ]){ 2 int a = 3; 3 int b = timesFive(a); 4 System.out.println(b+““); 5 } clear stack from local variables
A look into the JVM A look into the JVM Important: Every call to a method creates a new set of local variables ! These Variables are created on the stack and deleted when the method returns
Recursion Recursion
Recursion Recursion ,[object Object],[object Object],[object Object]
Recursion Recursion When you turn that into a program, you end up with functions that   call themselves: Recursive Functions
Recursion Recursion public int f(int a){ if (a==1)   return(1); else   return(a * f( a-1)); } It computes f! (factorial) What’s behind this function ?
Factorial Factorial:  a! = 1 * 2 * 3 * ... * (a-1) * a Note: a! = a * (a-1)! remember: ...splitting up the problem into a smaller problem of the same type... a! a  *  (a-1)!
Tracing the example public int factorial(int a){ if (a==0)   return(1); else   return(a * factorial( a-1)); } RECURSION !
Watching the Stack public int factorial(int a){ if (a==1)   return(1); else   return(a * factorial( a-1)); } a = 5 a = 5 a = 5 Return to L4 a = 4 Return to L4 a = 4 Return to L4 a = 3 Return to L4 a = 2 Return to L4 a = 1 Initial After 1 recursion After 4 th  recursion … Every call to the method creates a new set of local variables !
Watching the Stack public int factorial(int a){ if (a==1)   return(1); else   return(a * factorial( a-1)); } a = 5 Return to L4 a = 4 Return to L4 a = 3 Return to L4 a = 2 Return to L4 a = 1 After 4 th  recursion a = 5 Return to L4 a = 4 Return to L4 a = 3 Return to L4 a = 2*1 = 2 a = 5 Return to L4 a = 4 Return to L4 a = 3*2 = 6 a = 5 Return to L4 a = 4*6 = 24 a = 5*24 = 120 Result
Properties of Recursive Functions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Solution The recursive algorithms we write generally consist of an if statement: IF  the stopping case is reached solve it ELSE  split the problem into simpler cases using recursion Solution on stack Solution on stack Solution on stack
Common Programming Error Recursion does not terminate properly:  Stack Overflow !
Exercise Define a recursive solution for the following function: f(x) = x n
Recursion vs. Iteration You could have written the power-function  iteratively,  i.e. using a loop construction Where‘s the difference ?
Recursion vs. Iteration ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Deciding whether to use a Recursive Function ,[object Object],[object Object],[object Object]
Examples: Fractal Tree http://id.mind.net/~zona/mmts/geometrySection/fractals/tree/treeFractal.html
Examples: The 8 Queens Problem http://mossie.cs.und.ac.za/~murrellh/javademos/queens/queens.html Eight queens are to be placed on a chess board  in such a way that no queen checks against any other queen
Review ,[object Object],[object Object],[object Object],[object Object],[object Object]

Weitere ähnliche Inhalte

Was ist angesagt?

Principal source of optimization in compiler design
Principal source of optimization in compiler designPrincipal source of optimization in compiler design
Principal source of optimization in compiler designRajkumar R
 
(Recursion)ads
(Recursion)ads(Recursion)ads
(Recursion)adsRavi Rao
 
Iteration, induction, and recursion
Iteration, induction, and recursionIteration, induction, and recursion
Iteration, induction, and recursionMohammed Hussein
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting AlgorithmsAfaq Mansoor Khan
 
Recursion(Advanced data structure)
Recursion(Advanced data structure)Recursion(Advanced data structure)
Recursion(Advanced data structure)kurubameena1
 
Chapter 6 intermediate code generation
Chapter 6   intermediate code generationChapter 6   intermediate code generation
Chapter 6 intermediate code generationVipul Naik
 
A2 Computing Reverse Polish Notation Part 2
A2 Computing   Reverse Polish Notation Part 2A2 Computing   Reverse Polish Notation Part 2
A2 Computing Reverse Polish Notation Part 2pstevens1963
 
Lecture 03 lexical analysis
Lecture 03 lexical analysisLecture 03 lexical analysis
Lecture 03 lexical analysisIffat Anjum
 
Lecture 05 syntax analysis 2
Lecture 05 syntax analysis 2Lecture 05 syntax analysis 2
Lecture 05 syntax analysis 2Iffat Anjum
 
Matlab m files and scripts
Matlab m files and scriptsMatlab m files and scripts
Matlab m files and scriptsAmeen San
 
Lecture 11.2 : sorting
Lecture 11.2 :  sortingLecture 11.2 :  sorting
Lecture 11.2 : sortingVivek Bhargav
 

Was ist angesagt? (20)

Principal source of optimization in compiler design
Principal source of optimization in compiler designPrincipal source of optimization in compiler design
Principal source of optimization in compiler design
 
(Recursion)ads
(Recursion)ads(Recursion)ads
(Recursion)ads
 
Iteration, induction, and recursion
Iteration, induction, and recursionIteration, induction, and recursion
Iteration, induction, and recursion
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting Algorithms
 
Stability Analysis of Discrete System
Stability Analysis of Discrete SystemStability Analysis of Discrete System
Stability Analysis of Discrete System
 
Recursion(Advanced data structure)
Recursion(Advanced data structure)Recursion(Advanced data structure)
Recursion(Advanced data structure)
 
Ch8a
Ch8aCh8a
Ch8a
 
Chapter 6 intermediate code generation
Chapter 6   intermediate code generationChapter 6   intermediate code generation
Chapter 6 intermediate code generation
 
A2 Computing Reverse Polish Notation Part 2
A2 Computing   Reverse Polish Notation Part 2A2 Computing   Reverse Polish Notation Part 2
A2 Computing Reverse Polish Notation Part 2
 
C programming session5
C programming  session5C programming  session5
C programming session5
 
Lecture 03 lexical analysis
Lecture 03 lexical analysisLecture 03 lexical analysis
Lecture 03 lexical analysis
 
Lecture 05 syntax analysis 2
Lecture 05 syntax analysis 2Lecture 05 syntax analysis 2
Lecture 05 syntax analysis 2
 
User Defined Functions in C Language
User Defined Functions   in  C LanguageUser Defined Functions   in  C Language
User Defined Functions in C Language
 
User defined functions in matlab
User defined functions in  matlabUser defined functions in  matlab
User defined functions in matlab
 
LISP:Program structure in lisp
LISP:Program structure in lispLISP:Program structure in lisp
LISP:Program structure in lisp
 
Matlab m files and scripts
Matlab m files and scriptsMatlab m files and scripts
Matlab m files and scripts
 
Lecture 11.2 : sorting
Lecture 11.2 :  sortingLecture 11.2 :  sorting
Lecture 11.2 : sorting
 
Recursion in c
Recursion in cRecursion in c
Recursion in c
 
Compiler unit 2&3
Compiler unit 2&3Compiler unit 2&3
Compiler unit 2&3
 
Programming with matlab session 1
Programming with matlab session 1Programming with matlab session 1
Programming with matlab session 1
 

Andere mochten auch

Edtc 6340-66 copyright crash course alberto tudon 4th ed
Edtc 6340-66 copyright crash course  alberto tudon 4th edEdtc 6340-66 copyright crash course  alberto tudon 4th ed
Edtc 6340-66 copyright crash course alberto tudon 4th edalbertotudon
 
Fabulous pictures
Fabulous picturesFabulous pictures
Fabulous picturesLes Davy
 
10 planete infricosatoare
10 planete infricosatoare10 planete infricosatoare
10 planete infricosatoarebalada65
 
Ervasti: Kouluympäristö hyvinvoinnin tekijänä
Ervasti: Kouluympäristö hyvinvoinnin tekijänäErvasti: Kouluympäristö hyvinvoinnin tekijänä
Ervasti: Kouluympäristö hyvinvoinnin tekijänäKouluterveyskysely
 
Play decide: Malaria
Play decide: MalariaPlay decide: Malaria
Play decide: MalariaXplore Health
 
Subversion to Git Migration
Subversion to Git MigrationSubversion to Git Migration
Subversion to Git MigrationTim Massey
 
Microcontroladores ARM Cortex M0+ Aplicação em robôs autoguiados - Microcontr...
Microcontroladores ARM Cortex M0+ Aplicação em robôs autoguiados - Microcontr...Microcontroladores ARM Cortex M0+ Aplicação em robôs autoguiados - Microcontr...
Microcontroladores ARM Cortex M0+ Aplicação em robôs autoguiados - Microcontr...Fabio Souza
 
BA Netapp Event - Always there IT Infrastructuur
BA Netapp Event - Always there IT InfrastructuurBA Netapp Event - Always there IT Infrastructuur
BA Netapp Event - Always there IT InfrastructuurB.A.
 
World class manufacturing (wcm)
World class manufacturing (wcm)World class manufacturing (wcm)
World class manufacturing (wcm)Rahul Hedau
 
Kauppi: Mielikuvituksen ja fantasioiden merkitys nuorten mielenterveydessä ja...
Kauppi: Mielikuvituksen ja fantasioiden merkitys nuorten mielenterveydessä ja...Kauppi: Mielikuvituksen ja fantasioiden merkitys nuorten mielenterveydessä ja...
Kauppi: Mielikuvituksen ja fantasioiden merkitys nuorten mielenterveydessä ja...Kouluterveyskysely
 
What are the keys to success
What are the keys to successWhat are the keys to success
What are the keys to successAbhishek Saha
 
Identifying Volume
Identifying VolumeIdentifying Volume
Identifying Volumejmori1
 
Securing access inabyod-world-final-ext
Securing access inabyod-world-final-extSecuring access inabyod-world-final-ext
Securing access inabyod-world-final-extOracleIDM
 
Mortimore Shonga Farms, Nigeria - An ‘experiment’ in large-scale commercial f...
Mortimore Shonga Farms, Nigeria - An ‘experiment’ in large-scale commercial f...Mortimore Shonga Farms, Nigeria - An ‘experiment’ in large-scale commercial f...
Mortimore Shonga Farms, Nigeria - An ‘experiment’ in large-scale commercial f...futureagricultures
 
CSS Technieken Toegelicht
CSS Technieken ToegelichtCSS Technieken Toegelicht
CSS Technieken ToegelichtTweepixels
 
Elements, Compounds & Mixtures Day 3
Elements, Compounds & Mixtures Day 3Elements, Compounds & Mixtures Day 3
Elements, Compounds & Mixtures Day 3jmori1
 

Andere mochten auch (20)

Edtc 6340-66 copyright crash course alberto tudon 4th ed
Edtc 6340-66 copyright crash course  alberto tudon 4th edEdtc 6340-66 copyright crash course  alberto tudon 4th ed
Edtc 6340-66 copyright crash course alberto tudon 4th ed
 
Les clàssiques i els blogs
Les clàssiques i els blogsLes clàssiques i els blogs
Les clàssiques i els blogs
 
Fabulous pictures
Fabulous picturesFabulous pictures
Fabulous pictures
 
10 planete infricosatoare
10 planete infricosatoare10 planete infricosatoare
10 planete infricosatoare
 
Ervasti: Kouluympäristö hyvinvoinnin tekijänä
Ervasti: Kouluympäristö hyvinvoinnin tekijänäErvasti: Kouluympäristö hyvinvoinnin tekijänä
Ervasti: Kouluympäristö hyvinvoinnin tekijänä
 
Play decide: Malaria
Play decide: MalariaPlay decide: Malaria
Play decide: Malaria
 
Subversion to Git Migration
Subversion to Git MigrationSubversion to Git Migration
Subversion to Git Migration
 
Microcontroladores ARM Cortex M0+ Aplicação em robôs autoguiados - Microcontr...
Microcontroladores ARM Cortex M0+ Aplicação em robôs autoguiados - Microcontr...Microcontroladores ARM Cortex M0+ Aplicação em robôs autoguiados - Microcontr...
Microcontroladores ARM Cortex M0+ Aplicação em robôs autoguiados - Microcontr...
 
BA Netapp Event - Always there IT Infrastructuur
BA Netapp Event - Always there IT InfrastructuurBA Netapp Event - Always there IT Infrastructuur
BA Netapp Event - Always there IT Infrastructuur
 
World class manufacturing (wcm)
World class manufacturing (wcm)World class manufacturing (wcm)
World class manufacturing (wcm)
 
Kauppi: Mielikuvituksen ja fantasioiden merkitys nuorten mielenterveydessä ja...
Kauppi: Mielikuvituksen ja fantasioiden merkitys nuorten mielenterveydessä ja...Kauppi: Mielikuvituksen ja fantasioiden merkitys nuorten mielenterveydessä ja...
Kauppi: Mielikuvituksen ja fantasioiden merkitys nuorten mielenterveydessä ja...
 
What are the keys to success
What are the keys to successWhat are the keys to success
What are the keys to success
 
Identifying Volume
Identifying VolumeIdentifying Volume
Identifying Volume
 
Securing access inabyod-world-final-ext
Securing access inabyod-world-final-extSecuring access inabyod-world-final-ext
Securing access inabyod-world-final-ext
 
Imac all in one
Imac all in oneImac all in one
Imac all in one
 
Slide 1
Slide  1Slide  1
Slide 1
 
Mortimore Shonga Farms, Nigeria - An ‘experiment’ in large-scale commercial f...
Mortimore Shonga Farms, Nigeria - An ‘experiment’ in large-scale commercial f...Mortimore Shonga Farms, Nigeria - An ‘experiment’ in large-scale commercial f...
Mortimore Shonga Farms, Nigeria - An ‘experiment’ in large-scale commercial f...
 
CSS Technieken Toegelicht
CSS Technieken ToegelichtCSS Technieken Toegelicht
CSS Technieken Toegelicht
 
Elements, Compounds & Mixtures Day 3
Elements, Compounds & Mixtures Day 3Elements, Compounds & Mixtures Day 3
Elements, Compounds & Mixtures Day 3
 
Division
DivisionDivision
Division
 

Ähnlich wie Cis068 08

Module 01 Stack and Recursion
Module 01 Stack and RecursionModule 01 Stack and Recursion
Module 01 Stack and RecursionTushar B Kute
 
lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptxLizhen Shi
 
Ap Power Point Chpt8
Ap Power Point Chpt8Ap Power Point Chpt8
Ap Power Point Chpt8dplunkett
 
Lecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptxLecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptxAbuHuraira729502
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyTypesafe
 
Unit-I Recursion.pptx
Unit-I Recursion.pptxUnit-I Recursion.pptx
Unit-I Recursion.pptxajajkhan16
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad Fabernovel
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Codemotion
 
01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms NotesAndres Mendez-Vazquez
 
Scala for Machine Learning
Scala for Machine LearningScala for Machine Learning
Scala for Machine LearningPatrick Nicolas
 

Ähnlich wie Cis068 08 (20)

Module 01 Stack and Recursion
Module 01 Stack and RecursionModule 01 Stack and Recursion
Module 01 Stack and Recursion
 
lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptx
 
Ap Power Point Chpt8
Ap Power Point Chpt8Ap Power Point Chpt8
Ap Power Point Chpt8
 
Lecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptxLecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptx
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
 
LP.ppt
LP.pptLP.ppt
LP.ppt
 
FUNDAMETAL ALG.ppt
FUNDAMETAL ALG.pptFUNDAMETAL ALG.ppt
FUNDAMETAL ALG.ppt
 
Unit-I Recursion.pptx
Unit-I Recursion.pptxUnit-I Recursion.pptx
Unit-I Recursion.pptx
 
Ppt chapter12
Ppt chapter12Ppt chapter12
Ppt chapter12
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018
 
Lazy java
Lazy javaLazy java
Lazy java
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
recursion.ppt
recursion.pptrecursion.ppt
recursion.ppt
 
01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes
 
Scala for Machine Learning
Scala for Machine LearningScala for Machine Learning
Scala for Machine Learning
 
Savitch ch 04
Savitch ch 04Savitch ch 04
Savitch ch 04
 
recursion.ppt
recursion.pptrecursion.ppt
recursion.ppt
 

Mehr von FALLEE31188 (20)

Lecture4
Lecture4Lecture4
Lecture4
 
Lecture2
Lecture2Lecture2
Lecture2
 
L16
L16L16
L16
 
L2
L2L2
L2
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Functions
FunctionsFunctions
Functions
 
Field name
Field nameField name
Field name
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
Chapter14
Chapter14Chapter14
Chapter14
 
Chapt03
Chapt03Chapt03
Chapt03
 
C++lecture9
C++lecture9C++lecture9
C++lecture9
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C1320prespost
C1320prespostC1320prespost
C1320prespost
 
Brookshear 06
Brookshear 06Brookshear 06
Brookshear 06
 
Book ppt
Book pptBook ppt
Book ppt
 
Assignment 2
Assignment 2Assignment 2
Assignment 2
 
Assignment
AssignmentAssignment
Assignment
 

Kürzlich hochgeladen

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 

Kürzlich hochgeladen (20)

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 

Cis068 08

  • 1. Welcome to CIS 068 ! Lesson 8: Stacks and Recursion
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12. A look into the JVM A look into the JVM 1 public static void main(String args[ ]){ 2 int a = 3; 3 int b = timesFive(a); 4 System.out.println(b+““); 5 } a = 3 b c = 15 Temporary storage a = 3 b = 15
  • 13. A look into the JVM A look into the JVM 1 public static void main(String args[ ]){ 2 int a = 3; 3 int b = timesFive(a); 4 System.out.println(b+““); 5 } clear stack from local variables
  • 14. A look into the JVM A look into the JVM Important: Every call to a method creates a new set of local variables ! These Variables are created on the stack and deleted when the method returns
  • 16.
  • 17. Recursion Recursion When you turn that into a program, you end up with functions that call themselves: Recursive Functions
  • 18. Recursion Recursion public int f(int a){ if (a==1) return(1); else return(a * f( a-1)); } It computes f! (factorial) What’s behind this function ?
  • 19. Factorial Factorial: a! = 1 * 2 * 3 * ... * (a-1) * a Note: a! = a * (a-1)! remember: ...splitting up the problem into a smaller problem of the same type... a! a * (a-1)!
  • 20. Tracing the example public int factorial(int a){ if (a==0) return(1); else return(a * factorial( a-1)); } RECURSION !
  • 21. Watching the Stack public int factorial(int a){ if (a==1) return(1); else return(a * factorial( a-1)); } a = 5 a = 5 a = 5 Return to L4 a = 4 Return to L4 a = 4 Return to L4 a = 3 Return to L4 a = 2 Return to L4 a = 1 Initial After 1 recursion After 4 th recursion … Every call to the method creates a new set of local variables !
  • 22. Watching the Stack public int factorial(int a){ if (a==1) return(1); else return(a * factorial( a-1)); } a = 5 Return to L4 a = 4 Return to L4 a = 3 Return to L4 a = 2 Return to L4 a = 1 After 4 th recursion a = 5 Return to L4 a = 4 Return to L4 a = 3 Return to L4 a = 2*1 = 2 a = 5 Return to L4 a = 4 Return to L4 a = 3*2 = 6 a = 5 Return to L4 a = 4*6 = 24 a = 5*24 = 120 Result
  • 23.
  • 24. Solution The recursive algorithms we write generally consist of an if statement: IF the stopping case is reached solve it ELSE split the problem into simpler cases using recursion Solution on stack Solution on stack Solution on stack
  • 25. Common Programming Error Recursion does not terminate properly: Stack Overflow !
  • 26. Exercise Define a recursive solution for the following function: f(x) = x n
  • 27. Recursion vs. Iteration You could have written the power-function iteratively, i.e. using a loop construction Where‘s the difference ?
  • 28.
  • 29.
  • 30. Examples: Fractal Tree http://id.mind.net/~zona/mmts/geometrySection/fractals/tree/treeFractal.html
  • 31. Examples: The 8 Queens Problem http://mossie.cs.und.ac.za/~murrellh/javademos/queens/queens.html Eight queens are to be placed on a chess board in such a way that no queen checks against any other queen
  • 32.