Example Consider the following class specification for a class that stores a bunch of characters. /* class invariant *this bunch contains one or more char.

Slides:



Advertisements
Similar presentations
A queue is a linear, homogeneous, container that stores and dispenses its content in a FIFO manner. FIFO - First In First Out The first (most distant)
Advertisements

A software specification indicates the task (or some aspect of the task) that is supposed to be performed when software executes. Types of Specifications.
Some containers are called linear because their content (items) are stored in a single row (line). Which of the following are linear?  the rungs of a.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 12: Recursion.
Recursion. Binary search example postponed to end of lecture.
1 Introduction to Recursion  Introduction to Recursion  Example 1: Factorial  Example 2: Reversing Strings  Example 3: Fibonacci  Infinite Recursion.
Recursion … just in case you didn’t love loops enough …
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
Recursion.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Recursion In general there are two approaches to writing repetitive algorithms. One uses loops(while, do while and for): the other uses recursion. Recursion.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Data Structures Using C++ 2E Chapter 6 Recursion.
1 Chapter 18-1 Recursion Dale/Weems. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
Data Structures Using C++ 2E Chapter 6 Recursion.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 19 Recursion.
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Recursion A method is recursive if it makes a call to itself. A method is recursive if it makes a call to itself. For example: For example: public void.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
Recursion.  A recursive function contains a call to itself Example: the factorial n!=n*(n-1)! for n>1 n!=1 for n=1 int factorial (int n) { if (n == 0)
Programming Principles II Lecture Notes 5 Recursion Andreas Savva.
Software reuse means to “borrow” existing code. How can you reuse an existing class to make a new one? Such reuse is really an adaptation -- using the.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
Recursion. Recursive Methods HAVE: 1.A base case or termination condition that causes the method to end 2.A non-base case whose actions move the algorithm.
Cosc236/recursion1 Recursion Recursive method calls itself Recursion frequently occurs in mathematics Recursive definition –2 parts base part (basis) recursive.
10/14/2015cosc237/recursion1 Recursion A method of defining a concept which refers to the concept itself A method of solving a problem by reducing it to.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Sequential & Object oriented Programming
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Chapter 14 Recursion. Chapter Objectives Learn about recursive definitions Explore the base case and the general case of a recursive definition Learn.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Two Parts of Every ADT An abstract data type (ADT)  is a type for encapsulating related data  is abstract in the sense that it hides distracting implementation.
A queue is a linear, homogeneous, container that stores and dispenses its content in a FIFO manner. FIFO - Fast In First Out The first (most distant) item.
Recursion. Math Review Given the following sequence: a 1 = 1 a n = 2*a n-1 OR a n+1 = 2*a n What are the values of the following? a 2 = a 3 = a 4 =
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
 initially Treat data as N sorted collections that are each one datum long.  merge Merge each consecutive pair of collections to form sorted collections.
Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used.
Recursion A recursive definition is one which uses the word or concept being defined in the definition itself Example: “A computer is a machine.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
A software specification indicates the task (or some aspect of the task) that is supposed to be performed when software executes. Types of Specifications.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
R ECURRSION Prepared by Miss Simab Shahid Lecturer computer Science and Software Engineering department, University of Hail Chapter.
Recursion in Java The answer to life’s greatest mysteries are on the last slide.
Int fact (int n) { If (n == 0) return 1; else return n * fact (n – 1); } 5 void main () { Int Sum; : Sum = fact (5); : } Factorial Program Using Recursion.
Program Development and Design Using C++, Third Edition
Chapter 6 (Lafore’s Book) Recursion Hwajung Lee.  Definition: An algorithmic technique. To solve a problem on an instance of size n, the instance is:
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
1 7.Algorithm Efficiency These factors vary from one machine/compiler (platform) to another  Count the number of times instructions are executed So, measure.
Lecture 11 Recursion. A recursive function is a function that calls itself either directly, or indirectly through another function; it is an alternative.
Recursion Powerful Tool
Recursion Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems © 2004 Pearson Addison-Wesley.
Recursion DRILL: Please take out your notes on Recursion
Chapter 12 Recursion (methods calling themselves)
Recursion: The Mirrors
Recursion Chapter 11.
Recursion Data Structures.
Cs212: DataStructures Computer Science Department Lab 3 : Recursion.
Recursion.
Module 1-10: Recursion.
Java Programming: Chapter 9: Recursion Second Edition
Recursion: The Mirrors
The structure of programming
Yan Shi CS/SE 2630 Lecture Notes
CS148 Introduction to Programming II
ITEC324 Principle of CS III
Presentation transcript:

Example Consider the following class specification for a class that stores a bunch of characters. /* class invariant *this bunch contains one or more char *values stored in the order they are inserted */ /* post: this bunch consists of the char c */ public Bunch(char c) /* post: result == (number of chars in this) - loc */ public int countOfRemaining() /* pre: loc+1 <= number of chars in this * post: result == (loc+1)st char in this * and loc == + 1 */ public char nextChar() /* post: loc == 0 */ public void startNextChar()... Bunch Class Specifications Bunch - int loc «constructor» + Bunch(char c) «query» + int countOfRemaining() + char nextChar() «update» + void startNextChar() + void insert(char c) The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

What happens when the following code executes? public void printEm( Bunch b) { b.startNextChar(); while (b.countOfRemaining() > 0) { System.out.print( b.nextChar() ); } Q: How would you rewrite this method, using a loop to print the bunch in reverse? A: public void printEmReversed( Bunch b) { ?????? } The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

A recursive method is one that calls itself either directly or indirectly. Example /* post: all chars following loc have been output in reverse order */ public void printEmReversed(Bunch b) { char aChar; if ( b.countOfRemaining() > 0 ) { aChar = b.nextChar(); printEmReversed(b); System.out.print( aChar ); } The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Example /* post: all chars following loc have been output in reverse order */ public void printEmReversed(Bunch b) { char aChar; if ( b.countOfRemaining() > 0 ) { aChar = b.nextChar(); printEmReversed(b); System.out.print( aChar ); } /* assert: someBunch is a bunch consisting of ‘P’, ‘I’, ‘G’ */ SomeBunch.startNextChar(); printEmReversed( someBunch ); The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Each call results in a separate activation, and each activation has its own copy of local variables and parameter bindings. ACTIVATION 1 aChar == ? b public void printEmReversed(Bunch b) { char aChar; if ( b.countOfRemaining() > 0 ) { aChar = b.nextChar(); printEmReversed(b); System.out.print( aChar ); } someBunch : Bunch ‘P’ ‘I’ ‘G’ loc == 0 The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

How does the behavior of the following variation compare to the printEmReversed method from the preceding slides? /* post: all chars following loc have been output in reverse order */ public void printEmSomehow(Bunch b) { char aChar; if ( b.countOfRemaining() > 0 ) { aChar = b.nextChar(); System.out.print( aChar ); printEmSomehow(b); } The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

/* pre: n > 0 * post: result == the nth Fibonacci number */ public int nth_Fibonacci( int n) { } DEFINITION nth Fibonacci number Base The 1 st Fibonacci number is 0. The 2 nd Fibonacci number is 1. Recursive If A n-1 is the (n-1) st Fibonacci number and A n-2 is the (n-2) nd Fibonacci, then A n-1 + A n-2 is the nth Fibonacci. The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Before Fill (from location X )After Fill (in red) The task of coloring the white region from a point out to its surrounding colored boundary is sometimes called a fill algorithm. Consider a rectangular grid (rows and columns) of picture elements (pixels) where each pixel can be colored independently. The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Consider a rectangular grid (rows and columns) of picture elements (pixels) where each pixel can be colored independently. /* class invariant *rowCount >0 and colCount > 0 */ /* post: rowCount == rows and colCount == cols */ public PixelGrid(int rows, int cols) /* pre: 0 ≤ r ≤ rowCount-1 and 0 ≤ c ≤ colCount-1 * post: result == the pixel from row r and column c * is white in color */ public boolean isPixelWhite(int r, int c) /* pre: 0 ≤ r ≤ rowCount-1 and 0 ≤ c ≤ colCount-1 * post: The pixel in row r and column c is red */ public void setPixelRed(int r, int c)... PixelGrid Class Specifications PixelGrid - int rowCount - int colCount «constructor» + PixelGrid(int rows, int cols) «query» + boolean isPixelWhite(int r, int c)) «update» + void setPixelRed(int r, int c) columns rows The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Before Fill (from location X )After Fill (in red) /* pre: position (r, c) within grid is bordered by a closed figure of non-white cells * post: the old white region surrounding (r, c) with non-white border has been colored red */ public void fill(PixelGrid grid, int r, int c ) { if ( grid.isPixelWhite(r,c) ) { grid.setPixelRed(r, c); fill( grid, r-1, c ); fill( grid, r, c+1 ); fill( grid, r+1, c); fill( grid, r, c-1); } The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

public void fill(PixelGrid grid, int r, int c ) { if ( grid.isPixelWhite(r,c) ) { grid.setPixelRed(r, c); fill( grid, r-1, c ); fill( grid, r, c+1 ); fill( grid, r+1, c); fill( grid, r, c-1); } The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Recursion can be subtle. Describe the behavior of each of the following. public void fill2(PixelGrid grid, int r, int c ) { if ( grid.isPixelWhite(r,c) ) { fill2( grid, r-1, c ); fill2( grid, r, c+1 ); fill2( grid, r+1, c); fill2( grid, r, c-1); grid.setPixelRed(r, c); } public void fill3(PixelGrid grid, int r, int c ) { if ( grid.isPixelWhite(r,c) ) { grid.setPixelRed(r, c); fill3( grid, r-1, c-1 ); fill3( grid, r-1, c ); fill3( grid, r-1, c+1 ); fill3( grid, r, c+1 ); fill3( grid, r, c-1 ); fill3( grid, r+1, c-1 ); fill3( grid, r+1, c ); fill3( grid, r+1, c+1 ); } The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Anything that can be accomplished with a loop, can also be written recursively. while ( condition ) { loopBody; } General form of a while loop. Equivalent recursive method The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

Infinite recursion is analogous to an infinite loop, and possibly more likely. public void infWhile() { if ( condition ) { infWhile(); loopBody; } Every activation requires computer memory and computer time. If a convenient non-recursive algorithm exists, it is usually more efficient than a recursive option. The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.

/* pre: n >= 0 * post: result == n! */ public int factorial( int n ) { if ( n == 0) { return 1; } else { return n * factorial(n-1); } Recursive Method DEFINITION n factorial (written n!) Base 0! == 1 Recursive n! == n * (n-1)! for any integer n > 0 /* pre: n >= 0 * post: result == n! */ public int factorial2( int n ) { int result = 1; while ( n > 1 ) { result = result * n; n--; } A Better Solution Table-driven int[] factorialTable = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, , , , }; The Object of Data Abstraction and Structure, David D. Riley © Addison Wesley pub.