SlideShare une entreprise Scribd logo
1  sur  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]

Contenu connexe

Tendances

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
 

Tendances (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
 

En vedette

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
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Plus de 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
 

Dernier

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
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
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
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
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
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
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
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
_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
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
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
 
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
 
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
 

Dernier (20)

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
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
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
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
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
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
_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
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
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
 
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
 
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
 

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.