Welcome to CIS 068 ! Lesson 8:  Stacks and Recursion
Overview Subjects: Stacks Structure Methods Stacks and Method – Calls Recursion Principle Recursion and Stacks Recursion vs. Iteration Examples
Stacks: Introduction What do these tools have in common ? Plate Dispenser PEZ ® Dispenser
Stack: Properties Answer: They both provide LIFO (last in first out) Structures 1 2 3 4 5 6 1 2 3 4 5 6
Stacks: Properties Possible actions: PUSH an object (e.g. a plate) onto dispenser POP object out of dispenser
Stacks: Definition Stacks are LIFO structures, providing Add Item (=PUSH) Methods Remove Item (=POP) Methods They are a simple way to build a collection No indexing necessary Size of collection must not be predefined  But: extremely reduced accessibility
Stacks Application Areas LIFO order is desired See JVM-example on next slides ...or simply no order is necessary Lab-assignment 5: reading a collection of coordinates to draw
A look into the JVM Sample Code: 1  public static void main(String args[ ]){ 2 int a = 3; 3 int b = timesFive(a); 4 System.out.println(b+““); 5 } 6 Public int timesFive(int a){ 7 int b = 5;  8 int c = a * b; 9 return (c); 10  }
A look into the JVM Inside the JVM a stack is used to  create the local variables to store the return address from a call to pass the method-parameters
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 } 6 Public int timesFive(int a){ 7 int b = 5;  8 int c = a * b; 9 return (c); 10  } a = 3 a = 3 b Return to LINE 3 b = 5 c = 15
A look into the JVM ... return (c); ... 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 Sometimes, the best way to solve a problem is by solving a  smaller version  of the exact same problem first Recursion is a technique that solves a problem by solving a  smaller problem of the same type   A procedure that is defined in terms of itself
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 Problems that can be solved by recursion have these characteristics: One or more stopping cases have a simple, nonrecursive solution The other cases of the problem can be reduced (using recursion) to problems that are closer to stopping cases Eventually the problem can be reduced to only stopping cases, which are relatively easy to solve Follow these steps to solve a recursive problem: Try to express the problem as a simpler version of itself Determine the stopping cases Determine the recursive steps
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 Iteration can be used in place of recursion An iterative algorithm uses a  looping construct A recursive algorithm uses a  branching structure Recursive solutions are often less efficient, in terms of both  time  and  space , than iterative solutions Recursion can simplify the solution of a problem, often resulting in shorter, more easily understood source code   (Nearly) every recursively defined problem can be solved iteratively     iterative optimization can be implemented after recursive design
Deciding whether to use a Recursive Function When the depth of recursive calls is relatively “shallow” The recursive version does about the same amount of work as the nonrecursive version The recursive version is shorter and simpler than the  nonrecursive solution
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 A stack is a simple LIFO datastructure used e.g. by the JVM to create local variable spaces Recursion is a divide and conquer designing technique that often provides a simple algorithmic structure Recursion can be replaced by iteration for reasons of efficiency There is a connection between recursion and the use of stacks There are interesting problems out there that can be solved by recursion

More Related Content

PPT
Matlab 4
PPT
Data Structures- Part5 recursion
PPT
Ch10 Recursion
PPT
3 recursion
PDF
Iterations and Recursions
PPT
Recursion and looping
PPT
Recursion - Algorithms and Data Structures
PPTX
Principle source of optimazation
Matlab 4
Data Structures- Part5 recursion
Ch10 Recursion
3 recursion
Iterations and Recursions
Recursion and looping
Recursion - Algorithms and Data Structures
Principle source of optimazation

What's hot (20)

PPTX
Principal source of optimization in compiler design
PPTX
(Recursion)ads
PDF
Iteration, induction, and recursion
PPTX
Recursion and Sorting Algorithms
PPTX
Stability Analysis of Discrete System
PPTX
Recursion(Advanced data structure)
PPT
Chapter 6 intermediate code generation
PPT
A2 Computing Reverse Polish Notation Part 2
PDF
C programming session5
PPT
Lecture 03 lexical analysis
PPT
Lecture 05 syntax analysis 2
PDF
User Defined Functions in C Language
PDF
User defined functions in matlab
PPTX
LISP:Program structure in lisp
PPTX
Matlab m files and scripts
PPTX
Lecture 11.2 : sorting
PPT
Recursion in c
PDF
Compiler unit 2&3
PDF
Programming with matlab session 1
Principal source of optimization in compiler design
(Recursion)ads
Iteration, induction, and recursion
Recursion and Sorting Algorithms
Stability Analysis of Discrete System
Recursion(Advanced data structure)
Chapter 6 intermediate code generation
A2 Computing Reverse Polish Notation Part 2
C programming session5
Lecture 03 lexical analysis
Lecture 05 syntax analysis 2
User Defined Functions in C Language
User defined functions in matlab
LISP:Program structure in lisp
Matlab m files and scripts
Lecture 11.2 : sorting
Recursion in c
Compiler unit 2&3
Programming with matlab session 1
Ad

Viewers also liked (20)

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

Similar to Cis068 08 (20)

PDF
Module 01 Stack and Recursion
PPTX
Lecture_7_StackAndRecursion (1).pptx
PDF
Recursion For the Rest of Us (CS Fundamentals Series)
PPTX
Recursion is used in programming languages to use a procedure multiple times ...
PPTX
6 Recursion Using Python 1.pptx6 Recursion Using Python 1.pptx
PPTX
Recursion
PPTX
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
PPTX
Day 1 (1).pptx
PDF
Week11
PPT
FUNDAMETAL ALG.ppt
PDF
Programming in Java: Recursion
PPTX
Recursion in Data Structure
DOCX
Recursion in C++
PPT
Recursion.ppt
PPT
PPTX
Recursion Fundamrwersfsdfsdfsfsdfsdfsfsdfsdfsentals.pptx
PPTX
Unit-I Recursion.pptx
PDF
DS & Algo 2 - Recursion
PDF
recursion1
PPTX
Recursionaditya..................................pptx
Module 01 Stack and Recursion
Lecture_7_StackAndRecursion (1).pptx
Recursion For the Rest of Us (CS Fundamentals Series)
Recursion is used in programming languages to use a procedure multiple times ...
6 Recursion Using Python 1.pptx6 Recursion Using Python 1.pptx
Recursion
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
Day 1 (1).pptx
Week11
FUNDAMETAL ALG.ppt
Programming in Java: Recursion
Recursion in Data Structure
Recursion in C++
Recursion.ppt
Recursion Fundamrwersfsdfsdfsfsdfsdfsfsdfsdfsentals.pptx
Unit-I Recursion.pptx
DS & Algo 2 - Recursion
recursion1
Recursionaditya..................................pptx

More from FALLEE31188 (20)

PPT
Lecture4
PPT
Lecture2
PPT
PPTX
Inheritance
PDF
Inheritance
PPT
Functions
DOC
Field name
PPT
Encapsulation
PPT
Cpp tutorial
PPT
Chapter14
PPT
Chapt03
PPT
C++lecture9
PPT
C++ polymorphism
PPT
C++ classes tutorials
PPT
C1320prespost
PPT
Brookshear 06
PPT
Book ppt
PPTX
Assignment 2
PPTX
Assignment
Lecture4
Lecture2
Inheritance
Inheritance
Functions
Field name
Encapsulation
Cpp tutorial
Chapter14
Chapt03
C++lecture9
C++ polymorphism
C++ classes tutorials
C1320prespost
Brookshear 06
Book ppt
Assignment 2
Assignment

Recently uploaded (20)

PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
Complications of Minimal Access-Surgery.pdf
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PPTX
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
PDF
International_Financial_Reporting_Standa.pdf
PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
PPTX
Unit 4 Computer Architecture Multicore Processor.pptx
PPTX
Introduction to pro and eukaryotes and differences.pptx
PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PDF
advance database management system book.pdf
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
PDF
What if we spent less time fighting change, and more time building what’s rig...
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
My India Quiz Book_20210205121199924.pdf
PPTX
History, Philosophy and sociology of education (1).pptx
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Complications of Minimal Access-Surgery.pdf
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
LDMMIA Reiki Yoga Finals Review Spring Summer
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
International_Financial_Reporting_Standa.pdf
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
Paper A Mock Exam 9_ Attempt review.pdf.
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
Unit 4 Computer Architecture Multicore Processor.pptx
Introduction to pro and eukaryotes and differences.pptx
Environmental Education MCQ BD2EE - Share Source.pdf
advance database management system book.pdf
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
What if we spent less time fighting change, and more time building what’s rig...
A powerpoint presentation on the Revised K-10 Science Shaping Paper
My India Quiz Book_20210205121199924.pdf
History, Philosophy and sociology of education (1).pptx

Cis068 08

  • 1. Welcome to CIS 068 ! Lesson 8: Stacks and Recursion
  • 2. Overview Subjects: Stacks Structure Methods Stacks and Method – Calls Recursion Principle Recursion and Stacks Recursion vs. Iteration Examples
  • 3. Stacks: Introduction What do these tools have in common ? Plate Dispenser PEZ ® Dispenser
  • 4. Stack: Properties Answer: They both provide LIFO (last in first out) Structures 1 2 3 4 5 6 1 2 3 4 5 6
  • 5. Stacks: Properties Possible actions: PUSH an object (e.g. a plate) onto dispenser POP object out of dispenser
  • 6. Stacks: Definition Stacks are LIFO structures, providing Add Item (=PUSH) Methods Remove Item (=POP) Methods They are a simple way to build a collection No indexing necessary Size of collection must not be predefined But: extremely reduced accessibility
  • 7. Stacks Application Areas LIFO order is desired See JVM-example on next slides ...or simply no order is necessary Lab-assignment 5: reading a collection of coordinates to draw
  • 8. A look into the JVM Sample Code: 1 public static void main(String args[ ]){ 2 int a = 3; 3 int b = timesFive(a); 4 System.out.println(b+““); 5 } 6 Public int timesFive(int a){ 7 int b = 5; 8 int c = a * b; 9 return (c); 10 }
  • 9. A look into the JVM Inside the JVM a stack is used to create the local variables to store the return address from a call to pass the method-parameters
  • 10. 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 } 6 Public int timesFive(int a){ 7 int b = 5; 8 int c = a * b; 9 return (c); 10 } a = 3 a = 3 b Return to LINE 3 b = 5 c = 15
  • 11. A look into the JVM ... return (c); ... 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
  • 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. Recursion Recursion Sometimes, the best way to solve a problem is by solving a smaller version of the exact same problem first Recursion is a technique that solves a problem by solving a smaller problem of the same type A procedure that is defined in terms of itself
  • 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. Properties of Recursive Functions Problems that can be solved by recursion have these characteristics: One or more stopping cases have a simple, nonrecursive solution The other cases of the problem can be reduced (using recursion) to problems that are closer to stopping cases Eventually the problem can be reduced to only stopping cases, which are relatively easy to solve Follow these steps to solve a recursive problem: Try to express the problem as a simpler version of itself Determine the stopping cases Determine the recursive steps
  • 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. Recursion vs. Iteration Iteration can be used in place of recursion An iterative algorithm uses a looping construct A recursive algorithm uses a branching structure Recursive solutions are often less efficient, in terms of both time and space , than iterative solutions Recursion can simplify the solution of a problem, often resulting in shorter, more easily understood source code (Nearly) every recursively defined problem can be solved iteratively  iterative optimization can be implemented after recursive design
  • 29. Deciding whether to use a Recursive Function When the depth of recursive calls is relatively “shallow” The recursive version does about the same amount of work as the nonrecursive version The recursive version is shorter and simpler than the nonrecursive solution
  • 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. Review A stack is a simple LIFO datastructure used e.g. by the JVM to create local variable spaces Recursion is a divide and conquer designing technique that often provides a simple algorithmic structure Recursion can be replaced by iteration for reasons of efficiency There is a connection between recursion and the use of stacks There are interesting problems out there that can be solved by recursion