Presentation is loading. Please wait.

Presentation is loading. Please wait.

Principles of Programming and Software Engineering

Similar presentations


Presentation on theme: "Principles of Programming and Software Engineering"— Presentation transcript:

1 Principles of Programming and Software Engineering
Chapter 1 Principles of Programming and Software Engineering

2 Problem Solving and Software Engineering
Coding without a solution design increases debugging time A team of programmers for a large software development project involves An overall plan Organization Communication Software engineering Provides techniques to facilitate the development of computer programs © 2005 Pearson Addison-Wesley. All rights reserved

3 What is Problem Solving?
The process of taking the statement of a problem and developing a computer program that solves that problem A solution consists of: Algorithms Algorithm: a step-by-step specification of a function to solve a problem within a finite amount of time Ways to store data © 2005 Pearson Addison-Wesley. All rights reserved

4 The Life Cycle of Software
Figure 1.1 The life cycle of software as a waterwheel that can rotate from one phase to any other phase © 2005 Pearson Addison-Wesley. All rights reserved

5 The Life Cycle of Software
Phase 1: Specification Aspects of the problem which must be specified: What is the input data? What data is valid and what data is invalid? Who will use the software, and what user interface should be used? What error detection and error messages are desirable? What assumptions are possible? Are there special cases? What is the form of the output? What documentation is necessary? What enhancements to the program are likely in the future? © 2005 Pearson Addison-Wesley. All rights reserved

6 The Life Cycle of Software
Phase 1: Specification (Continued) Prototype program A program that simulates the behavior of portions of the desired software product Phase 2: Design Includes: Dividing the program into modules Specifying the purpose of each module Specifying the data flow among modules © 2005 Pearson Addison-Wesley. All rights reserved

7 The Life Cycle of Software
Phase 2: Design (Continued) Modules Self-contained units of code Should be designed to be: Loosely coupled Highly cohesive Interfaces Communication mechanisms among modules © 2005 Pearson Addison-Wesley. All rights reserved

8 The Life Cycle of Software
Phase 2: Design (Continued) Specifications of a function A contract between the function and the module that calls it Should not commit the function to a particular way of performing its task Include the function’s preconditions and postconditions Phase 3: Risk Analysis Building software entails risks Techniques exist to identify, assess, and manage the risks of creating a software product © 2005 Pearson Addison-Wesley. All rights reserved

9 The Life Cycle of Software
Phase 4: Verification Formal methods can be used to prove that an algorithm is correct Assertion A statement about a particular condition at a certain point in an algorithm Invariant A condition that is always true at a particular point in an algorithm © 2005 Pearson Addison-Wesley. All rights reserved

10 The Life Cycle of Software
Phase 4: Verification (Continued) Loop invariant A condition that is true before and after each execution of an algorithm’s loop Can be used to detect errors before coding is started The invariant for a correct loop is true: Initially, after any initialization steps, but before the loop begins execution Before every iteration of the loop After every iteration of the loop After the loop terminates © 2005 Pearson Addison-Wesley. All rights reserved

11 The Life Cycle of Software
Phase 5: Coding (Continued) Involves: Translating the design into a particular programming language Removing syntax errors Phase 6: Testing Removing the logical errors © 2005 Pearson Addison-Wesley. All rights reserved

12 The Life Cycle of Software
Phase 6: Testing (Continued) Test data should include: Valid data that leads to a known result Invalid data Random data Actual data Phase 7: Refining the Solution More sophisticated input and output routines Additional features More error checks © 2005 Pearson Addison-Wesley. All rights reserved

13 The Life Cycle of Software
Phase 8: Production Involves: Distribution to the intended users Use by the users Phase 9: Maintenance Involves Correcting user-detected errors Adding more features Modifying existing portions to suit the users better © 2005 Pearson Addison-Wesley. All rights reserved

14 What is a Good Solution? A solution is good if:
The total cost it incurs over all phases of its life cycle is minimal © 2005 Pearson Addison-Wesley. All rights reserved

15 What is a Good Solution? The cost of a solution includes:
Computer resources that the program consumes Difficulties encountered by users Consequences of a program that does not behave correctly Programs must be well structured and documented Efficiency is one aspect of a solution’s cost © 2005 Pearson Addison-Wesley. All rights reserved

16 Achieving a Modular Design: Abstraction
Separates the purpose of a module from its implementation Specifications for each module are written before implementation Functional abstraction Separates the purpose of a function from its implementation © 2005 Pearson Addison-Wesley. All rights reserved

17 Achieving a Modular Design
Data abstraction Focuses of the operations of data, not on the implementation of the operations Abstract data type (ADT) A collection of data and operations on the data An ADT’s operations can be used without knowing how the operations are implemented, if the operations’ specifications are known © 2005 Pearson Addison-Wesley. All rights reserved

18 Achieving a Modular Design
Data structure A construct that can be defined within a programming language to store a collection of data © 2005 Pearson Addison-Wesley. All rights reserved

19 Achieving a Modular Design
Information hiding Hide details within a module Ensure that no other module can tamper with these hidden details Public view of a module Described by its specifications Private view of a module Consists of details which should not be described by the specifications © 2005 Pearson Addison-Wesley. All rights reserved

20 Object-Oriented Design
Principles of object-oriented programming (OOP) Encapsulation Objects combine data and operations Inheritance Classes can inherit properties from other classes Polymorphism Objects can determine appropriate operations at execution time © 2005 Pearson Addison-Wesley. All rights reserved

21 Object-Oriented Design
Advantages of an object-oriented approach Existing classes can be reused Program maintenance and verification are easier © 2005 Pearson Addison-Wesley. All rights reserved

22 Top-Down Design Object-oriented design (OOD)
Produces modular solutions for problems that primarily involve data Identifies objects by focusing on the nouns in the problem statement © 2005 Pearson Addison-Wesley. All rights reserved

23 Top-Down Design Top-down design (TDD)
Produces modular solutions for problems in which the emphasis is on the algorithms Identifies actions by focusing on the verbs in the problem statement A task is addressed at successively lower levels of detail © 2005 Pearson Addison-Wesley. All rights reserved

24 Top-Down Design Figure 1.4
A structure chart showing the hierarchy of modules © 2005 Pearson Addison-Wesley. All rights reserved

25 General Design Guidelines
Use OOD and TDD together Use OOD for problems that primarily involve data Use TDD to design algorithms for an object’s operations © 2005 Pearson Addison-Wesley. All rights reserved

26 General Design Guidelines
Consider TDD to design solutions to problems that emphasize algorithms over data Focus on what, not how, when designing both ADTs and algorithms Consider incorporating previously written software components into your design © 2005 Pearson Addison-Wesley. All rights reserved

27 Modeling Object-Oriented Design Using UML
The Unified Modeling Language (UML) is a modeling language used to express object-oriented designs Class diagrams specify the name of the class, the data members of the class, and the operations © 2005 Pearson Addison-Wesley. All rights reserved

28 Modeling Object-Oriented Design Using UML
UML (Continued) Relationships between classes can be shown by connecting classes with lines Inheritance is shown with a line and an open triangle to the parent class Containment is shown with an arrow to the containing class UML provides notation to specify visibility, type, parameter, and default value information © 2005 Pearson Addison-Wesley. All rights reserved

29 UML Diagrams Figure 1.6 UML diagram for a banking system
© 2005 Pearson Addison-Wesley. All rights reserved

30 A Summary of Key Issues in Programming
Modularity has a favorable impact on Constructing programs Debugging programs Reading programs Modifying programs Eliminating redundant code © 2005 Pearson Addison-Wesley. All rights reserved

31 A Summary of Key Issues in Programming
Modifiability is possible through the use of Function Named constants The typedef statement © 2005 Pearson Addison-Wesley. All rights reserved

32 A Summary of Key Issues in Programming
Ease of use In an interactive environment, the program should prompt the user for input in a clear manner A program should always echo its input The output should be well labeled and easy to read © 2005 Pearson Addison-Wesley. All rights reserved

33 A Summary of Key Issues in Programming
Fail-Safe Programming Fail-safe programs will perform reasonably no matter how anyone uses it Test for invalid input data and program logic errors Handle errors through exception handling © 2005 Pearson Addison-Wesley. All rights reserved

34 A Summary of Key Issues in Programming
Eight issues of personal style in programming Extensive use of functions Use of private data fields Avoidance of global variables in functions Proper use of reference arguments © 2005 Pearson Addison-Wesley. All rights reserved

35 A Summary of Key Issues in Programming
Eight issues of personal style in programming (Continued) Proper use of functions Error handling Readability Documentation © 2005 Pearson Addison-Wesley. All rights reserved

36 A Summary of Key Issues in Programming
Debugging Programmer must systematically check a program’s logic to determine where an error occurs Tools to use while debugging: Watches Breakpoints cout statements Dump functions © 2005 Pearson Addison-Wesley. All rights reserved

37 Summary Software engineering: techniques to facilitate development of programs Software life cycle consists of nine phases Loop invariant: property that is true before and after each iteration of a loop Evaluating the quality of a solution must consideration a variety of factors © 2005 Pearson Addison-Wesley. All rights reserved

38 Summary A combination of object-oriented and top-down design techniques leads to a modular solution The final solution should be as easy to modify as possible A function should be as independent as possible and perform one well-defined task © 2005 Pearson Addison-Wesley. All rights reserved

39 Summary Functions should include a comment: purpose, precondition, and postcondition A program should be as fail-safe as possible Effective use of available diagnostic aids is one of the keys to debugging Use “dump functions” to help to examine and debug the contents of data structures © 2005 Pearson Addison-Wesley. All rights reserved

40 Recursion: The Mirrors
Chapter 2 Recursion: The Mirrors

41 Recursive Solutions Recursion is an extremely powerful problem-solving technique Breaks a problem in smaller identical problems An alternative to iteration, which involves loops A sequential search is iterative Starts at the beginning of the collection Looks at every item in the collection in order © 2005 Pearson Addison-Wesley. All rights reserved

42 Recursive Solutions A binary search is recursive
Repeatedly halves the collection and determines which half could contain the item Uses a divide and conquer strategy © 2005 Pearson Addison-Wesley. All rights reserved

43 Recursive Solutions Facts about a recursive solution
A recursive method calls itself Each recursive call solves an identical, but smaller, problem A test for the base case enables the recursive calls to stop Base case: a known case in a recursive definition Eventually, one of the smaller problems must be the base case © 2005 Pearson Addison-Wesley. All rights reserved

44 Recursive Solutions Four questions for construction recursive solutions How can you define the problem in terms of a smaller problem of the same type? How does each recursive call diminish the size of the problem? © 2005 Pearson Addison-Wesley. All rights reserved

45 Recursive Solutions Four questions for construction recursive solutions (Continued) What instance of the problem can serve as the base case? As the problem size diminishes, will you reach this base case? © 2005 Pearson Addison-Wesley. All rights reserved

46 A Recursive Valued Method: The Factorial of n
Problem Compute the factorial of an integer n An iterative definition of factorial(n) factorial(n) = n * (n-1) * (n-2) * … * 1 for any integer n > 0 factorial(0) = 1 © 2005 Pearson Addison-Wesley. All rights reserved

47 A Recursive Valued Method: The Factorial of n
A recursive definition of factorial(n) factorial(n) = 1 if n = 0 n * factorial(n-1) if n > 0 © 2005 Pearson Addison-Wesley. All rights reserved

48 A Recursive Valued Method: The Factorial of n
A recurrence relation A mathematical formula that generates the terms in a sequence from previous terms Example factorial(n) = n * [(n-1) * (n-2) * … * 1] = n * factorial(n-1) © 2005 Pearson Addison-Wesley. All rights reserved

49 A Recursive Valued Method: The Factorial of n
Box trace A systematic way to trace the actions of a recursive method Each box roughly corresponds to an activation record Contains a function’s local environment at the time of and as a result of the call to the method © 2005 Pearson Addison-Wesley. All rights reserved

50 A Recursive Valued Method: The Factorial of n
Figure 2.3 A box © 2005 Pearson Addison-Wesley. All rights reserved

51 A Recursive Valued Method: The Factorial of n
A function’s local environment includes: The function’s local variables A copy of the actual value arguments A return address in the calling routine The value of the function itself © 2005 Pearson Addison-Wesley. All rights reserved

52 A Recursive void Method: Writing a String Backward
Problem Given a string of characters, write it in reverse order Recursive solution Each recursive step of the solution diminishes by 1 the length of the string to be written backward Base case: write the empty string backward © 2005 Pearson Addison-Wesley. All rights reserved

53 A Recursive void Method: Writing a String Backward
Execution of writeBackward can be traced using the box trace Temporary cout statements can be used to debug a recursive method © 2005 Pearson Addison-Wesley. All rights reserved

54 A Recursive void Method: Writing a String Backward
Figure 2.6 A recursive solution © 2005 Pearson Addison-Wesley. All rights reserved

55 Multiplying Rabbits (The Fibonacci Sequence)
“Facts” about rabbits Rabbits never die A rabbit reaches sexual maturity exactly two months after birth, that is, at the beginning of its third month of life At the beginning of every month, each sexually mature male-female pair gives birth to exactly one male-female pair © 2005 Pearson Addison-Wesley. All rights reserved

56 Multiplying Rabbits (The Fibonacci Sequence)
Problem How many pairs of rabbits are alive in month n? Recurrence relation rabbit(n) = rabbit(n-1) + rabbit(n-2) © 2005 Pearson Addison-Wesley. All rights reserved

57 Multiplying Rabbits (The Fibonacci Sequence)
Figure Recursive solution to the rabbit problem © 2005 Pearson Addison-Wesley. All rights reserved

58 Multiplying Rabbits (The Fibonacci Sequence)
Base cases rabbit(2), rabbit(1) Recursive definition rabbit(n) = if n is 1 or 2 rabbit(n-1) + rabbit(n-2) if n > 2 Fibonacci sequence The series of numbers rabbit(1), rabbit(2), rabbit(3), and so on © 2005 Pearson Addison-Wesley. All rights reserved

59 Organizing a Parade Problem
How many ways can you organize a parade of length n? The parade will consist of bands and floats in a single line One band cannot be placed immediately after another © 2005 Pearson Addison-Wesley. All rights reserved

60 Organizing a Parade Let: Then
P(n) be the number of ways to organize a parade of length n F(n) be the number of parades of length n that end with a float B(n) be the number of parades of length n that end with a band Then P(n) = F(n) + B(n) © 2005 Pearson Addison-Wesley. All rights reserved

61 Organizing a Parade Number of acceptable parades of length n that end with a float F(n) = P(n-1) Number of acceptable parades of length n that end with a band B(n) = F(n-1) Number of acceptable parades of length n P(n) = P(n-1) + P(n-2) © 2005 Pearson Addison-Wesley. All rights reserved

62 Organizing a Parade Base cases
P(1) = 2 (The parades of length 1 are float and band.) P(2) = 3 (The parades of length 2 are float-float, band-float, and float- band.) © 2005 Pearson Addison-Wesley. All rights reserved

63 Organizing a Parade Solution P(1) = 2 P(2) = 3
P(n) = P(n-1) + P(n-2) for n > 2 © 2005 Pearson Addison-Wesley. All rights reserved

64 Mr. Spock’s Dilemma (Choosing k out of n Things)
Problem How many different choices are possible for exploring k planets out of n planets in a solar system? © 2005 Pearson Addison-Wesley. All rights reserved

65 Mr. Spock’s Dilemma (Choosing k out of n Things)
Let c(n, k) be the number of groups of k planets chosen from n In terms of Planet X: c(n, k) = the number of groups of k planets that include Planet X + the number of groups of k planets that do not include Planet X © 2005 Pearson Addison-Wesley. All rights reserved

66 Mr. Spock’s Dilemma (Choosing k out of n Things)
The number of ways to choose k out of n things is the sum of The number of ways to choose k-1 out of n-1 things and the number of ways to choose k out of n-1 things c(n, k) = c(n-1, k-1) + c(n-1, k) © 2005 Pearson Addison-Wesley. All rights reserved

67 Mr. Spock’s Dilemma (Choosing k out of n Things)
Base cases There is one group of everything c(k, k) = 1 There is one group of nothing c(n, 0) = 1 c(n, k) = 0 if k > n © 2005 Pearson Addison-Wesley. All rights reserved

68 Mr. Spock’s Dilemma (Choosing k out of n Things)
Recursive solution c(n, k) = 1 if k = 0 if k = n if k > n c(n-1, k-1) + c(n-1, k) if 0 < k < n © 2005 Pearson Addison-Wesley. All rights reserved

69 Mr. Spock’s Dilemma (Choosing k out of n Things)
Figure The recursive calls that c(4, 2) generates © 2005 Pearson Addison-Wesley. All rights reserved

70 Searching an Array: Finding the Largest Item in an Array
A recursive solution if (anArray has only one item) { maxArray(anArray) is the item in anArray } else if (anArray has more than one item) { maxArray(anArray) is the maximum of maxArray(left half of anArray) and maxArray(right half of anArray) } // end if © 2005 Pearson Addison-Wesley. All rights reserved

71 Searching an Array: Finding the Largest Item in an Array
Figure Recursive solution to the largest-item problem © 2005 Pearson Addison-Wesley. All rights reserved

72 Binary Search A high-level binary search
if (anArray is of size 1) { Determine if anArray’s item is equal to value } else { Find the midpoint of anArray Determine which half of anArray contains value if (value is in the first half of anArray) { binarySearch (first half of anArray, value) binarySearch(second half of anArray, value) } // end if © 2005 Pearson Addison-Wesley. All rights reserved

73 Binary Search Implementation issues:
How will you pass “half of anArray” to the recursive calls to binarySearch? How do you determine which half of the array contains value? What should the base case(s) be? How will binarySearch indicate the result of the search? © 2005 Pearson Addison-Wesley. All rights reserved

74 Finding the kth Smallest Item in an Array
The recursive solution proceeds by: Selecting a pivot item in the array Cleverly arranging, or partitioning, the items in the array about this pivot item Recursively applying the strategy to one of the partitions © 2005 Pearson Addison-Wesley. All rights reserved

75 Finding the kth Smallest Item in an Array
Figure A partition about a pivot © 2005 Pearson Addison-Wesley. All rights reserved

76 Finding the kth Smallest Item in an Array
Let: kSmall(k, anArray, first, last) = kth smallest item in anArray[first..last] © 2005 Pearson Addison-Wesley. All rights reserved

77 Finding the kth Smallest Item in an Array
Solution: kSmall(k, anArray, first, last) = kSmall(k,anArray,first,pivotIndex-1) if k < pivotIndex – first + 1 = p if k = pivotIndex – first + 1 = kSmall(k-(pivotIndex-first+1), anArray, pivotIndex+1, last) if k > pivotIndex – first + 1 © 2005 Pearson Addison-Wesley. All rights reserved

78 Organizing Data: The Towers of Hanoi
Figure 2.19a and b a) The initial state; b) move n - 1 disks from A to C © 2005 Pearson Addison-Wesley. All rights reserved

79 The Towers of Hanoi Figure 2.19c and d c) move one disk from A to B; d) move n - 1 disks from C to B © 2005 Pearson Addison-Wesley. All rights reserved

80 The Towers of Hanoi Pseudocode solution
solveTowers(count, source, destination, spare) if (count is 1) { Move a disk directly from source to destination } else { solveTowers(count-1, source, spare, destination) solveTowers(1, source, destination, spare) solveTowers(count-1, spare, destination, source) } //end if © 2005 Pearson Addison-Wesley. All rights reserved

81 Recursion and Efficiency
Some recursive solutions are so inefficient that they should not be used Factors that contribute to the inefficiency of some recursive solutions Overhead associated with method calls Inherent inefficiency of some recursive algorithms © 2005 Pearson Addison-Wesley. All rights reserved

82 Recursion and Efficiency
Do not use a recursive solution if it is inefficient and there is a clear, efficient iterative solution © 2005 Pearson Addison-Wesley. All rights reserved

83 Summary Recursion solves a problem by solving a smaller problem of the same type Four questions: How can you define the problem in terms of a smaller problem of the same type? How does each recursive call diminish the size of the problem? What instance of the problem can serve as the base case? As the problem size diminishes, will you reach this base case? © 2005 Pearson Addison-Wesley. All rights reserved

84 Summary A recursive call’s postcondition can be assumed to be true if its precondition is true The box trace can be used to trace the actions of a recursive method Recursion can be used to solve problems whose iterative solutions are difficult to conceptualize © 2005 Pearson Addison-Wesley. All rights reserved

85 Summary Some recursive solutions are much less efficient than a corresponding iterative solution due to their inherently inefficient algorithms and the overhead of method calls If you can easily, clearly, and efficiently solve a problem by using iteration, you should do so © 2005 Pearson Addison-Wesley. All rights reserved

86 Data Abstraction: The Walls
Chapter 3 Data Abstraction: The Walls

87 Abstract Data Types Modularity
Keeps the complexity of a large program manageable by systematically controlling the interaction of its components Isolates errors © 2005 Pearson Addison-Wesley. All rights reserved

88 Abstract Data Types Modularity (Continued) Eliminates redundancies
A modular program is Easier to write Easier to read Easier to modify © 2005 Pearson Addison-Wesley. All rights reserved

89 Abstract Data Types Procedural abstraction
Separates the purpose and use of a module from its implementation A module’s specifications should Detail how the module behaves Identify details that can be hidden within the module © 2005 Pearson Addison-Wesley. All rights reserved

90 Abstract Data Types Information hiding
Hides certain implementation details within a module Makes these details inaccessible from outside the module © 2005 Pearson Addison-Wesley. All rights reserved

91 Abstract Data Types Figure 3.1
Isolated tasks: the implementation of task T does not affect task Q © 2005 Pearson Addison-Wesley. All rights reserved

92 Abstract Data Types The isolation of modules is not total
Functions’ specifications, or contracts, govern how they interact with each other Figure 3.2 A slit in the wall © 2005 Pearson Addison-Wesley. All rights reserved

93 Abstract Data Types Typical operations on data
Add data to a data collection Remove data from a data collection Ask questions about the data in a data collection © 2005 Pearson Addison-Wesley. All rights reserved

94 Abstract Data Types Data abstraction
Asks you to think what you can do to a collection of data independently of how you do it Allows you to develop each data structure in relative isolation from the rest of the solution A natural extension of procedural abstraction © 2005 Pearson Addison-Wesley. All rights reserved

95 Abstract Data Types Abstract data type (ADT) An ADT is composed of
A collection of data A set of operations on that data Specifications of an ADT indicate What the ADT operations do, not how to implement them Implementation of an ADT Includes choosing a particular data structure © 2005 Pearson Addison-Wesley. All rights reserved

96 Abstract Data Types Figure 3.4
A wall of ADT operations isolates a data structure from the program that uses it © 2005 Pearson Addison-Wesley. All rights reserved

97 The ADT List Except for the first and last items, each item has a unique predecessor and a unique successor Head or front do not have a predecessor Tail or end do not have a successor © 2005 Pearson Addison-Wesley. All rights reserved

98 The ADT List Items are referenced by their position within the list
Specifications of the ADT operations Define the contract for the ADT list Do not specify how to store the list or how to perform the operations ADT operations can be used in an application without the knowledge of how the operations will be implemented © 2005 Pearson Addison-Wesley. All rights reserved

99 The ADT List ADT List operations Create an empty list
Determine whether a list is empty Determine the number of items in a list Add an item at a given position in the list Remove the item at a given position in the list Remove all the items from the list Retrieve (get) item at a given position in the list © 2005 Pearson Addison-Wesley. All rights reserved

100 The ADT List The ADT sorted list Maintains items in sorted order
Inserts and deletes items by their values, not their positions © 2005 Pearson Addison-Wesley. All rights reserved

101 The ADT List Figure 3.7 The wall between displayList and the implementation of the ADT list © 2005 Pearson Addison-Wesley. All rights reserved

102 Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does a problem require? What operations does a problem require? © 2005 Pearson Addison-Wesley. All rights reserved

103 Designing an ADT For complex abstract data types, the behavior of the operations must be specified using axioms Axiom: A mathematical rule Ex. : (aList.createList()).size() = 0 © 2005 Pearson Addison-Wesley. All rights reserved

104 Implementing ADTs Choosing the data structure to represent the ADT’s data is a part of implementation Choice of a data structure depends on Details of the ADT’s operations Context in which the operations will be used © 2005 Pearson Addison-Wesley. All rights reserved

105 Implementing ADTs Implementation details should be hidden behind a wall of ADT operations A program would only be able to access the data structure using the ADT operations © 2005 Pearson Addison-Wesley. All rights reserved

106 Implementing ADTs Figure 3.8
ADT operations provide access to a data structure © 2005 Pearson Addison-Wesley. All rights reserved

107 Implementing ADTs Figure 3.9 Violating the wall of ADT operations
© 2005 Pearson Addison-Wesley. All rights reserved

108 C++ Classes Encapsulation combines an ADT’s data with its operations to form an object An object is an instance of a class A class contains data members and member functions By default, all members in a class are private © 2005 Pearson Addison-Wesley. All rights reserved

109 C++ Classes Each class definition is placed in a header file
Classname.h The implementation of a class’s member functions are placed in an implementation file Classname.cpp © 2005 Pearson Addison-Wesley. All rights reserved

110 C++ Classes Figure 3.10 An object’s data and methods are encapsulated
© 2005 Pearson Addison-Wesley. All rights reserved

111 Class Constructors and Destructors
Create and initialize new instances of a class Have the same name as the class Have no return type, not even void © 2005 Pearson Addison-Wesley. All rights reserved

112 Class Constructors and Destructors
A class can have several constructors A default constructor has no arguments Initializers can set data members to initial values The compiler will generate a default constructor if one is omitted © 2005 Pearson Addison-Wesley. All rights reserved

113 Class Constructors and Destructors
The implementation of a constructor (or any member function) is qualified with the scope resolution operator :: Sphere::Sphere(double initialRadius) : theRadius(initialRadius) © 2005 Pearson Addison-Wesley. All rights reserved

114 Class Constructors and Destructors
Destroy an instance of an object when the object’s lifetime ends Each class has one destructor For many classes, the destructor can be omitted The compiler will generate a default constructor if one is omitted © 2005 Pearson Addison-Wesley. All rights reserved

115 Inheritance in C++ A derived class or subclass inherits any of the publicly defined functions or data members of a base class or superclass © 2005 Pearson Addison-Wesley. All rights reserved

116 Inheritance in C++ An instance of a derived class can invoke public methods of the base class: #include “Sphere.h” enum Color {RED, BLUE, GREEN, YELLOW} class ColoredSphere: public Sphere { public: Color getColor() const; © 2005 Pearson Addison-Wesley. All rights reserved

117 C++ Namespaces A mechanism for logically grouping declarations and definitions into a common declarative region © 2005 Pearson Addison-Wesley. All rights reserved

118 C++ Namespaces The contents of the namespace can be accessed by code inside or outside the namespace Use the scope resolution operator to access elements from outside the namespace Alternatively, the using declaration allows the names of the elements to be used directly © 2005 Pearson Addison-Wesley. All rights reserved

119 C++ Namespaces Creating a namespace Using a namespace
namespace smallNamespace { int count = 0; void abc(); } //end smallNamespace Using a namespace using namespace smallNamespace; count +=1; abc(); © 2005 Pearson Addison-Wesley. All rights reserved

120 C++ Namespaces Items declared in the C++ Standard Library are declared in the std namespace C++ include files for several functions are in the std namespace To include input and output functions from the C++ library, write include <iostream> using namespace std; © 2005 Pearson Addison-Wesley. All rights reserved

121 An Array-Based ADT List
A list’s items are stored in an array items Both an array and a list identify their items by number © 2005 Pearson Addison-Wesley. All rights reserved

122 An Array-Based ADT List
A list’s kth item will be stored in items[k-1] Figure An array-based implementation of the ADT list © 2005 Pearson Addison-Wesley. All rights reserved

123 C++ Exceptions Exception
A mechanism for handling an error during execution A function indicates that an error has occurred by throwing an exception The code that deals with the exception is said to catch or handle it © 2005 Pearson Addison-Wesley. All rights reserved

124 C++ Exceptions Throwing exceptions
A throw statement is used to throw an exception throw ExceptionClass (stringArgument); © 2005 Pearson Addison-Wesley. All rights reserved

125 C++ Exceptions try block
A statement that might throw an exception is placed within a try block Syntax try { statement(s); } // end try © 2005 Pearson Addison-Wesley. All rights reserved

126 C++ Exceptions catch block
Used to catch an exception and deal with the error condition Syntax catch (exceptionClass identifier) { statement(s); } // end catch © 2005 Pearson Addison-Wesley. All rights reserved

127 C++ Exceptions A programmer-define ListException class
#include <exception> #include <string> using namespace std; class ListException: public exception { public: ListException (const string & message = “”) : exception(message.c_str()) {} }; // end ListException © 2005 Pearson Addison-Wesley. All rights reserved

128 Summary Data abstraction controls the interaction between a program and its data structures Abstract data type (ADT): a set of data-management operations together with the data values upon which they operate Mathematical study of ADTs uses axioms to specify the behavior of ADT operations An ADT should be fully defined before any implementation decisions © 2005 Pearson Addison-Wesley. All rights reserved

129 Summary Hide an ADT’s implementation by defining the ADT as a C++ class An object encapsulates both data and operations A class contains at least one constructor and a destructor The compiler generates default constructor and destructor if none are provided © 2005 Pearson Addison-Wesley. All rights reserved

130 Summary Members of a class are private by default
Data members are typically private Public functions can be provided to access them Define and implement a class within header and implementation files Namespace: a mechanism to group classes, functions, variables, types, and constants Use exception handling to throw, catch, and handle errors during program execution © 2005 Pearson Addison-Wesley. All rights reserved

131 Chapter 4 Linked Lists

132 Preliminaries Options for implementing an ADT List
Array has a fixed size Data must be shifted during insertions and deletions Linked list is able to grow in size as needed Does not require the shifting of items during insertions and deletions © 2005 Pearson Addison-Wesley. All rights reserved

133 Preliminaries Figure 4.1 a) A linked list of integers; b) insertion; c) deletion © 2005 Pearson Addison-Wesley. All rights reserved

134 Pointers A pointer contains the location, or address in memory, of a memory cell Initially undefined, but not NULL A statically allocated pointer declaration int *p; A dynamically allocated pointer variable p = new int; © 2005 Pearson Addison-Wesley. All rights reserved

135 Pointers The expression, *p, denotes the memory cell to which p points
The & address-of operator places the address of a variable into a pointer variable p = &x; Figure 4.2 A pointer to an integer © 2005 Pearson Addison-Wesley. All rights reserved

136 Pointers The delete operator returns dynamically allocated memory to the system for reuse, and leaves the variable undefined delete p; A pointer to a deallocated memory cell is possible and dangerous Assign the pointer q the value in p q = p; © 2005 Pearson Addison-Wesley. All rights reserved

137 Pointers Figure 4.3 (a) declaring pointer variables; (b) pointing to statically allocating memory; (c) assigning a value; (d) allocating memory dynamically; (e) assigning a value © 2005 Pearson Addison-Wesley. All rights reserved

138 Pointers Figure 4.3 (f) copying a pointer;
(g) allocating memory dynamically and assigning a value; (h) assigning NULL to a pointer variable; (i) deallocating memory © 2005 Pearson Addison-Wesley. All rights reserved

139 Dynamic Allocation of Arrays
Use the new operator to allocate an array dynamically An array name is a pointer to the array’s first element The size of a dynamically allocated array can be increased double* oldArray = anArray; anArray = new double[2*arraySize]; © 2005 Pearson Addison-Wesley. All rights reserved

140 Pointer-Based Linked Lists
A node in a linked list is usually a struct struct Node { int item Node *next; }; //end struct A node is dynamically allocated Node *p; p = new Node; Figure 4.6 A node © 2005 Pearson Addison-Wesley. All rights reserved

141 Pointer-Based Linked Lists
The head pointer points to the first node in a linked list If head is NULL, the linked list is empty Executing the statement the statement head=new Node before head=NULL will result in a lost cell © 2005 Pearson Addison-Wesley. All rights reserved

142 Pointer-Based Linked Lists
Figure 4.7 A head pointer to a list Figure 4.8 A lost cell © 2005 Pearson Addison-Wesley. All rights reserved

143 Displaying the Contents of a Linked List
Reference a node member with the -> operator p->item; A traverse operation visits each node in the linked list A pointer variable cur keeps track of the current node for (Node *cur = head; cur != NULL; cur = cur->next) cout << cur->item << endl; © 2005 Pearson Addison-Wesley. All rights reserved

144 Displaying the Contents of a Linked List
Figure 4.9 The effect of the assignment cur = cur->next © 2005 Pearson Addison-Wesley. All rights reserved

145 Deleting a Specified Node from a Linked List
Deleting an interior node prev->next=cur->next; Deleting the first node head=head->next; Return deleted node to system cur->next = NULL; delete cur; cur=NULL; © 2005 Pearson Addison-Wesley. All rights reserved

146 Deleting a Specified Node from a Linked List
Figure Deleting a node from a linked list Figure Deleting the first node © 2005 Pearson Addison-Wesley. All rights reserved

147 Inserting a Node into a Specified Position of a Linked List
To insert a node between two nodes newPtr->next = cur; prev->next = newPtr; Figure 4.12 Inserting a new node into a linked list © 2005 Pearson Addison-Wesley. All rights reserved

148 Inserting a Node into a Specified Position of a Linked List
To insert a node at the beginning of a linked list newPtr->next = head; head = newPtr; Figure 4.13 Inserting at the beginning of a linked list © 2005 Pearson Addison-Wesley. All rights reserved

149 Inserting a Node into a Specified Position of a Linked List
Inserting at the end of a linked list is not a special case if cur is NULL newPtr->next = cur; prev->next = newPtr; Figure 4.14 Inserting at the end of a linked list © 2005 Pearson Addison-Wesley. All rights reserved

150 Inserting a Node into a Specified Position of a Linked List
Determining the point of insertion or deletion for a sorted linked list of objects for(prev = NULL, cur= head; (cur != null)&& (newValue > cur->item); prev = cur, cur = cur->next; © 2005 Pearson Addison-Wesley. All rights reserved

151 A Pointer-Based Implementation of the ADT List
Public methods isEmpty getLength insert remove retrieve Private method find Private Data Members head Size Local variables to member functions cur prev © 2005 Pearson Addison-Wesley. All rights reserved

152 Constructors and Destructors
Default constructor initializes size and head Copy constructor allows a deep copy Copies the array of list items and the number of items A destructor is required for dynamically allocated memory © 2005 Pearson Addison-Wesley. All rights reserved

153 Comparing Array-Based and Pointer-Based Implementations
Size Increasing the size of a resizable array can waste storage and time Storage requirements Array-based implementations require less memory than a pointer-based ones © 2005 Pearson Addison-Wesley. All rights reserved

154 Comparing Array-Based and Pointer-Based Implementations
Access time Array-based: constant access time Pointer-based: the time to access the ith node depends on i Insertion and deletions Array-based: require shifting of data Pointer-based: require a list traversal © 2005 Pearson Addison-Wesley. All rights reserved

155 Saving and Restoring a Linked List by Using a File
Use an external file to preserve the list between runs Do not write pointers to a file, only data Recreate the list from the file by placing each item at the end of the list Use a tail pointer to facilitate adding nodes to the end of the list Treat the first insertion as a special case by setting the tail to head © 2005 Pearson Addison-Wesley. All rights reserved

156 Passing a Linked List to a Function
A function with access to a linked list’s head pointer has access to the entire list Pass the head pointer to a function as a reference argument Figure A head pointer as a value argument © 2005 Pearson Addison-Wesley. All rights reserved

157 Processing Linked Lists Recursively
Recursive strategy to display a list Write the first node of the list Write the list minus its first node Recursive strategies to display a list backward writeListBackward strategy Write the last node of the list Write the list minus its last node backward © 2005 Pearson Addison-Wesley. All rights reserved

158 Processing Linked Lists Recursively
writeListBackward2 strategy Write the list minus its first node backward Write the first node of the list Recursive view of a sorted linked list The linked list to which head points is a sorted list if head is NULL or head->next is NULL or head->item < head->next->item, and head->next points to a sorted linked list © 2005 Pearson Addison-Wesley. All rights reserved

159 Objects as Linked List Data
Data in a linked list node can be an instance of a class typedef ClassName ItemType; struct Node { ItemType item; Node *next; }; //end struct Node *head; © 2005 Pearson Addison-Wesley. All rights reserved

160 Circular Linked Lists Last node references the first node
Every node has a successor No node in a circular linked list contains NULL Figure A circular linked list © 2005 Pearson Addison-Wesley. All rights reserved

161 Dummy Head Nodes Dummy head node
Always present, even when the linked list is empty Insertion and deletion algorithms initialize prev to reference the dummy head node, rather than NULL Figure A dummy head node © 2005 Pearson Addison-Wesley. All rights reserved

162 Doubly Linked Lists Each node points to both its predecessor and its successor Circular doubly linked list precede pointer of the dummy head node points to the last node next reference of the last node points to the dummy head node No special cases for insertions and deletions © 2005 Pearson Addison-Wesley. All rights reserved

163 Doubly Linked Lists Figure (a) A circular doubly linked list with a dummy head node (b) An empty list with a dummy head node © 2005 Pearson Addison-Wesley. All rights reserved

164 Doubly Linked Lists To delete the node to which cur points
(cur->precede)->next = cur->next; (cur->next)->precede = cur->precede; To insert a new node pointed to by newPtr before the node pointed to by cur newPtr->next = cur; newPtr->precede = cur->precede; cur->precede = newPtr; newPtr->precede->next = newPtr; © 2005 Pearson Addison-Wesley. All rights reserved

165 Application: Maintaining an Inventory
Operations on the inventory List the inventory in alphabetical order by title (L command) Find the inventory item associated with title (I, M, D, O, and S commands) Replace the inventory item associated with a title (M, D, R, and S commands) Insert new inventory items (A and D commands) © 2005 Pearson Addison-Wesley. All rights reserved

166 The C++ Standard Template Library
The STL contains class templates for some common ADTs, including the list class The STL provides support for predefined ADTs through three basic items Containers are objects that hold other objects Algorithms act on containers Iterators provide a way to cycle through the contents of a container © 2005 Pearson Addison-Wesley. All rights reserved

167 Summary The C++ new and delete operators enable memory to be dynamically allocated and recycled Each pointer in a linked list is a pointer to the next node in the list Array-based lists use an implicit ordering scheme; pointer-based lists use an explicit ordering scheme © 2005 Pearson Addison-Wesley. All rights reserved

168 Summary Algorithms for insertions and deletions in a linked list involve traversing the list and performing pointer changes Inserting a node at the beginning of a list and deleting the first node of a list are special cases A class that allocates memory dynamically needs an explicit copy constructor and destructor © 2005 Pearson Addison-Wesley. All rights reserved

169 Summary Recursion can be used to perform operations on a linked list
In a circular linked list, the last node points to the first node Dummy head nodes eliminate the special cases for insertion into and deletion from the beginning of a linked list © 2005 Pearson Addison-Wesley. All rights reserved

170 Recursion as a Problem-Solving Technique
Chapter 5 Recursion as a Problem-Solving Technique

171 Backtracking Backtracking
A strategy for guessing at a solution and backing up when an impasse is reached Recursion and backtracking can be combined to solve problems Eight-Queens Problem Place eight queens on the chessboard so that no queen can attack any other queen © 2005 Pearson Addison-Wesley. All rights reserved

172 The Eight Queens Problem
One strategy: guess at a solution There are 4,426,165,368 ways to arrange 8 queens on a chessboard of 64 squares An observation that eliminates many arrangements from consideration No queen can reside in a row or a column that contains another queen Now: only 40,320 (8!) arrangements of queens to be checked for attacks along diagonals © 2005 Pearson Addison-Wesley. All rights reserved

173 The Eight Queens Problem
Providing organization for the guessing strategy Place queens one column at a time If you reach an impasse, backtrack to the previous column Figure 5.2 A solution to the Eight Queens problem © 2005 Pearson Addison-Wesley. All rights reserved

174 The Eight Queens Problem
A recursive algorithm that places a queen in a column Base case If there are no more columns to consider You are finished Recursive step If you successfully place a queen in the current column Consider the next column If you cannot place a queen in the current column You need to backtrack © 2005 Pearson Addison-Wesley. All rights reserved

175 The Eight Queens Problem
Figure 5.1 a) Five queens that cannot attack each other, but that can attack all of column 6; b) backtracking to column 5 to try another square for the queen; c) backtracking to column 4 to try another square for the queen and then considering column 5 again © 2005 Pearson Addison-Wesley. All rights reserved

176 Implementing Eight Queens Using the STL Class vector
A Board object represents the chessboard Contains a vector of pointers to Queen objects on the board Includes operations to perform the Eight Queens problem and display the solution A Queen object represents a queen on the board Keeps track of its row and column placement Contains a static pointer to the Board © 2005 Pearson Addison-Wesley. All rights reserved

177 Defining Languages A language A set of strings of symbols
Examples: English, C++ If a C++ program is one long string of characters, the language C++Programs is defined as C++Programs = {strings w : w is a syntactically correct C++ program} © 2005 Pearson Addison-Wesley. All rights reserved

178 Defining Languages A language does not have to be a programming or a communication language Example: AlgebraicExpressions = {w : w is an algebraic expression} The grammar defines the rules for forming the strings in a language A recognition algorithm determines whether a given string is in the language A recognition algorithm for a language is written more easily with a recursive grammar © 2005 Pearson Addison-Wesley. All rights reserved

179 The Basics of Grammars Symbols used in grammars x | y means x or y
x y means x followed by y In x • y, the symbol • means concatenate, or append < word > means any instance of word that the definition defines © 2005 Pearson Addison-Wesley. All rights reserved

180 C++ Identifiers A C++ identifier begins with a letter and is followed by zero or more letters and digits Language C++Ids = {w : w is a legal C++ identifier} Grammar < identifier > = < letter > | < identifier > < letter > | < identifier > < digit> < letter > = a | b | … | z | A | B | …| Z | _ | $ < digit > = 0 | 1 | … | 9 © 2005 Pearson Addison-Wesley. All rights reserved

181 C++ Identifiers Recognition algorithm isId(in w:string): boolean
if (w is of length 1) if (w is a letter) return true else return false else if (the last character of w is a letter or a digit) return isId(w minus its last character) © 2005 Pearson Addison-Wesley. All rights reserved

182 Palindromes A string that reads the same from left to right as it does from right to left Language Palindromes = {w : w reads the same left to right as right to left} Grammar < pal > = empty string | < ch > | a < pal > a | b < pal > b | …| Z < pal > Z < ch > = a | b | … | z | A | B | … | Z © 2005 Pearson Addison-Wesley. All rights reserved

183 Palindromes Recognition algorithm isPal(in w:string):boolean
if (w is the empty string or w is of length 1) return true else if (w’s first and last characters are the same letter ) return isPal(w minus its first and last characters) else return false © 2005 Pearson Addison-Wesley. All rights reserved

184 Strings of the Form AnBn
The string that consists of n consecutive A’s followed by n consecutive B’s Language L = {w : w is of the form AnBn for some n ≥ 0} Grammar < legal-word > = empty string | A < legal-word > B © 2005 Pearson Addison-Wesley. All rights reserved

185 Strings of the form AnBn
Recognition algorithm isAnBn(in w:string):boolean if (the length of w is zero) return true else if (w begins with the character A and ends with the character B) return isAnBn(w minus its first and last characters) else return false © 2005 Pearson Addison-Wesley. All rights reserved

186 Algebraic Expressions
Infix expressions An operator appears between its operands Example: a + b Prefix expressions An operator appears before its operands Example: + a b Postfix expressions An operator appears after its operands Example: a b + © 2005 Pearson Addison-Wesley. All rights reserved

187 Algebraic Expressions
To convert a fully parenthesized infix expression to a prefix form Move each operator to the position marked by its corresponding open parenthesis Remove the parentheses Example Infix expression: ((a + b) * c Prefix expression: * + a b c © 2005 Pearson Addison-Wesley. All rights reserved

188 Algebraic Expressions
To convert a fully parenthesized infix expression to a postfix form Move each operator to the position marked by its corresponding closing parenthesis Remove the parentheses Example Infix form: ((a + b) * c) Postfix form: a b + c * © 2005 Pearson Addison-Wesley. All rights reserved

189 Algebraic Expressions
Prefix and postfix expressions Never need Precedence rules Association rules Parentheses Have Simple grammar expressions Straightforward recognition and evaluation algorithms © 2005 Pearson Addison-Wesley. All rights reserved

190 Prefix Expressions Grammar A recognition algorithm
< prefix > = < identifier > | < operator > < prefix > < prefix > < operator > = + | - | * | / < identifier > = a | b | … | z A recognition algorithm isPre():boolean lastChar = endPre(0) // returns the end return (lastChar >=0 and lastChar == strExp.length() -1) © 2005 Pearson Addison-Wesley. All rights reserved

191 Prefix Expressions An algorithm that evaluates a prefix expression
evaluatePrefix(inout strExp:string):float ch = first character of expression strExp Delete first character from strExp if (ch is an identifier) return value of the identifier else if (ch is an operator named op) { operand1 = evaluatePrefix(strExp) operand2 = evaluatePrefix(strExp) return operand1 op operand2 } © 2005 Pearson Addison-Wesley. All rights reserved

192 Postfix Expressions Grammar
< postfix > = < identifier > | < postfix > < postfix > < operator> < operator > = + | - | * | / < identifier > = a | b | … | z The recursive case for prefix form to postfix form conversion postfix(exp)= postfix(prefix1) + postfix(prefix2) + <operator> © 2005 Pearson Addison-Wesley. All rights reserved

193 Postfix Expressions A recursive algorithm that converts a prefix expression to postfix form convert(inout pre:string, out post:string) ch = first character of pre Delete first character of pre if (ch is a lowercase letter) post = post + ch else { convert(pre, post) } © 2005 Pearson Addison-Wesley. All rights reserved

194 Fully Parenthesized Expressions
Do not require precedence rules or rules for association Are inconvenient for programmers Grammar < infix > = < identifier > | (< infix > < operator > < infix > ) < operator > = + | - | * | / < identifier > = a | b | … | z © 2005 Pearson Addison-Wesley. All rights reserved

195 Recursion and Mathematical Induction
Both use a base case to solve a problem Both solve smaller problems of the same type to derive a solution Induction can be used to Prove properties about recursive algorithms Prove that a recursive algorithm performs a certain amount of work © 2005 Pearson Addison-Wesley. All rights reserved

196 The Correctness of the Recursive Factorial Function
Pseudocode for the recursive factorial if (n is 0) return 1 else return n * fact(n – 1) Induction on n proves the return values: fact(0) = 0! = 1 fact(n) = n!= n*(n – 1)* (n – 2)*…* 1 if n > 0 © 2005 Pearson Addison-Wesley. All rights reserved

197 The Cost of Towers of Hanoi
Solution to the Towers of Hanoi problem solveTowers(count, source, destination, spare) if (count is 1) Move a disk directly from source to destination else { solveTowers(count-1, source, spare, destination) solveTowers(1, source, destination, spare) solveTowers(count-1, spare, destination, source) } © 2005 Pearson Addison-Wesley. All rights reserved

198 The Cost of Towers of Hanoi
With N disks, how many moves does solveTowers make? Let moves(N) be the number of moves made starting with N disks When N = 1 moves(1) = 1 When N > 1 moves(N) = moves(N–1)+ moves(1) + moves(N–1) © 2005 Pearson Addison-Wesley. All rights reserved

199 The Cost of Towers of Hanoi
Recurrence relation for the number of moves that solveTowers requires for N disks moves(1) = 1 moves(N) = 2 * moves(N – 1) + 1 if N > 1 © 2005 Pearson Addison-Wesley. All rights reserved

200 The Cost of Towers of Hanoi
A closed-form formula is more satisfactory You can substitute any given value for N and obtain the number of moves made moves(N) = 2N – 1, for all N ≥ 1 Induction on N can provide the proof that moves(N) = 2N – 1 © 2005 Pearson Addison-Wesley. All rights reserved

201 Summary Backtracking is a solution strategy that involves both recursion and a sequence of guesses that ultimately lead to a solution A grammar is a device for defining a language A language is a set of strings of symbols A recognition algorithm for a language can often be based directly on the grammar of the language Grammars are frequently recursive © 2005 Pearson Addison-Wesley. All rights reserved

202 Summary Different languages of algebraic expressions have their relative advantages and disadvantages Prefix Postfix Infix Induction can be used to prove properties about a recursive algorithm © 2005 Pearson Addison-Wesley. All rights reserved

203 Chapter 6 Stacks

204 The Abstract Data Type Specifications of an abstract data type for a particular problem Can emerge during the design of the problem’s solution Examples readAndCorrect algorithm displayBackward algorithm © 2005 Pearson Addison-Wesley. All rights reserved

205 Developing an ADT During the Design of a Solution
ADT stack operations Create an empty stack Destroy a stack Determine whether a stack is empty Add a new item Remove the item that was added most recently Retrieve the item that was added most recently © 2005 Pearson Addison-Wesley. All rights reserved

206 Developing an ADT During the Design of a Solution
A stack Last-in, first-out (LIFO) property The last item placed on the stack will be the first item removed Analogy A stack of dishes in a cafeteria Figure 6.1 Stack of cafeteria dishes © 2005 Pearson Addison-Wesley. All rights reserved

207 Refining the Definition of the ADT Stack
Definitions for the ADT stack operations +createStack() +destroyStack() +isEmpty():boolean {query} +push(in newItem:StackItemType) throw StackException © 2005 Pearson Addison-Wesley. All rights reserved

208 Refining the Definition of the ADT Stack
Definitions for the ADT stack operations +pop() throw StackException +pop(out stackTop:StackItemType) throw StackException +getTop(out stackTop:StackItemType) {query} © 2005 Pearson Addison-Wesley. All rights reserved

209 Using the ADT Stack in a Solution
A program can use a stack independently of the stack’s implementation displayBackward and readAndCorrect algorithms can be refined using stack operations Define an ADT stack formally with axioms Specify that the last item inserted is the first item to be removed (aStack.push(newItem)).pop()= aStack © 2005 Pearson Addison-Wesley. All rights reserved

210 Checking for Balanced Braces
A stack can be used to verify whether a program contains balanced braces An example of balanced braces abc{defg{ijk}{l{mn}}op}qr An example of unbalanced braces abc{def}}{ghij{kl}m © 2005 Pearson Addison-Wesley. All rights reserved

211 Checking for Balanced Braces
Requirements for balanced braces Each time you encounter a “}”, it matches an already encountered “{” When you reach the end of the string, you have matched each “{” © 2005 Pearson Addison-Wesley. All rights reserved

212 Checking for Balanced Braces
Figure 6.3 Traces of the algorithm that checks for balanced braces © 2005 Pearson Addison-Wesley. All rights reserved

213 Recognizing Strings in a Language
L = {w$w’ : w is a possible empty string of characters other than $, w’ = reverse(w) } A solution using a stack Traverse the first half of the string, pushing each character onto a stack Once you reach the $, for each character in the second half of the string, match a popped character off the stack © 2005 Pearson Addison-Wesley. All rights reserved

214 Implementations of the ADT Stack
The ADT stack can be implemented using An array A linked list The ADT list All three implementations use a StackException class to handle possible exceptions © 2005 Pearson Addison-Wesley. All rights reserved

215 Implementations of the ADT Stack
Figure 6.4 Implementation of the ADT stack that use a) an array; b) a linked list; c) an ADT list © 2005 Pearson Addison-Wesley. All rights reserved

216 An Array-Based Implementation of the ADT Stack
Private data fields An array of items of type StackItemType The index top Compiler-generated destructor and copy constructor Figure 6.5 An array-based implementation © 2005 Pearson Addison-Wesley. All rights reserved

217 A Pointer-Based Implementation of the ADT Stack
Required when the stack needs to grow and shrink dynamically top is a reference to the head of a linked list of items A copy constructor and destructor must be supplied Figure 6.6 A pointer-based implementation © 2005 Pearson Addison-Wesley. All rights reserved

218 An Implementation That Uses the ADT List
The ADT list can be used to represent the items in a stack If the item in position 1 is the top push(newItem) insert(1, newItem) pop() remove(1) getTop(stackTop) retrieve(1, stackTop) © 2005 Pearson Addison-Wesley. All rights reserved

219 An Implementation That Uses the ADT List
Figure 6.7 An implementation that uses the ADT list © 2005 Pearson Addison-Wesley. All rights reserved

220 Comparing Implementations
Fixed size versus dynamic size An array-based implementation Prevents the push operation from adding an item to the stack if the stack’s size limit has been reached A pointer-based implementation Does not put a limit on the size of the stack © 2005 Pearson Addison-Wesley. All rights reserved

221 Comparing Implementations
An implementation that uses a linked list versus one that uses a pointer-based implementation of the ADT list Linked list approach is more efficient ADT list approach reuses an already implemented class Much simpler to write Saves time © 2005 Pearson Addison-Wesley. All rights reserved

222 The STL Class stack Provides a size function
Has two data type parameters T, the data type for the stack items Container, the container class that the STL uses in its implementation of the STL stack Uses the keyword explicit in the constructor to prevent invoking the constructor with the assignment operator © 2005 Pearson Addison-Wesley. All rights reserved

223 Application: Algebraic Expressions
When the ADT stack is used to solve a problem, the use of the ADT’s operations should not depend on its implementation To evaluate an infix expression Convert the infix expression to postfix form Evaluate the postfix expression © 2005 Pearson Addison-Wesley. All rights reserved

224 Evaluating Postfix Expressions
A postfix calculator When an operand is entered, the calculator Pushes it onto a stack When an operator is entered, the calculator Applies it to the top two operands of the stack Pops the operands from the stack Pushes the result of the operation on the stack © 2005 Pearson Addison-Wesley. All rights reserved

225 Evaluating Postfix Expressions
Figure 6.8 The action of a postfix calculator when evaluating the expression 2 * (3 + 4) © 2005 Pearson Addison-Wesley. All rights reserved

226 Evaluating Postfix Expressions
To evaluate a postfix expression which is entered as a string of characters Simplifying assumptions The string is a syntactically correct postfix expression No unary operators are present No exponentiation operators are present Operands are single lowercase letters that represent integer values © 2005 Pearson Addison-Wesley. All rights reserved

227 Converting Infix Expressions to Equivalent Postfix Expressions
An infix expression can be evaluated by first being converted into an equivalent postfix expression Facts about converting from infix to postfix Operands always stay in the same order with respect to one another An operator will move only “to the right” with respect to the operands All parentheses are removed © 2005 Pearson Addison-Wesley. All rights reserved

228 Converting Infix Expressions to Equivalent Postfix Expressions
Figure 6.9 A trace of the algorithm that converts the infix expression a - (b + c * d)/e to postfix form © 2005 Pearson Addison-Wesley. All rights reserved

229 Application: A Search Problem
High Planes Airline Company (HPAir) For each customer request, indicate whether a sequence of HPAir flights exists from the origin city to the destination city The flight map for HPAir is a graph Adjacent vertices are two vertices that are joined by an edge A directed path is a sequence of directed edges © 2005 Pearson Addison-Wesley. All rights reserved

230 Application: A Search Problem
Figure 6.10 Flight map for HPAir © 2005 Pearson Addison-Wesley. All rights reserved

231 A Nonrecursive Solution That Uses a Stack
The solution performs an exhaustive search Beginning at the origin city, the solution will try every possible sequence of flights until either It finds a sequence that gets to the destination city It determines that no such sequence exists Backtracking can be used to recover from a wrong choice of a city © 2005 Pearson Addison-Wesley. All rights reserved

232 A Nonrecursive Solution That Uses a Stack
Figure 6.13 A trace of the search algorithm, given the flight map in Figure 6-10 © 2005 Pearson Addison-Wesley. All rights reserved

233 A Recursive Solution Possible outcomes of the recursive search strategy You eventually reach the destination city and can conclude that it is possible to fly from the origin to the destination You reach a city C from which there are no departing flights You go around in circles © 2005 Pearson Addison-Wesley. All rights reserved

234 A Recursive Solution A refined recursive search strategy
+searchR(in originCity:City, in destinationCity:City):boolean Mark originCity as visited if (originCity is destinationCity) Terminate -- the destination is reached else for (each unvisited city C adjacent to originCity) searchR(C, destinationCity) © 2005 Pearson Addison-Wesley. All rights reserved

235 The Relationship Between Stacks and Recursion
Typically, stacks are used by compilers to implement recursive methods During execution, each recursive call generates an activation record that is pushed onto a stack Stacks can be used to implement a nonrecursive version of a recursive algorithm © 2005 Pearson Addison-Wesley. All rights reserved

236 Summary ADT stack operations have a last-in, first-out (LIFO) behavior
Stack applications Algorithms that operate on algebraic expressions Flight maps A strong relationship exists between recursion and stacks © 2005 Pearson Addison-Wesley. All rights reserved

237 Chapter 7 Queues

238 The Abstract Data Type Queue
A queue New items enter at the back, or rear, of the queue Items leave from the front of the queue First-in, first-out (FIFO) property The first item inserted into a queue is the first item to leave © 2005 Pearson Addison-Wesley. All rights reserved

239 The Abstract Data Type Queue
Queues Are appropriate for many real-world situations Example: A line to buy a movie ticket Have applications in computer science Example: A request to print a document A simulation A study to see how to reduce the wait involved in an application © 2005 Pearson Addison-Wesley. All rights reserved

240 The Abstract Data Type Queue
ADT queue operations Create an empty queue Destroy a queue Determine whether a queue is empty Add a new item to the queue Remove the item that was added earliest Retrieve the item that was added earliest © 2005 Pearson Addison-Wesley. All rights reserved

241 The Abstract Data Type Queue
Definitions for the ADT queue operations +createQueue() +destroyQueue() +isEmpty():boolean {query} +enqueue(in newItem:QueueItemType)throw QueueException © 2005 Pearson Addison-Wesley. All rights reserved

242 The Abstract Data Type Queue
Definitions for the ADT queue operations +dequeue() throw QueueException +dequeue(out queueFront:QueueItemType) throw QueueException +getFront(out queueFront:QueueItemType) throw QueueException © 2005 Pearson Addison-Wesley. All rights reserved

243 The Abstract Data Type Queue
Figure 7.2 Some queue operations © 2005 Pearson Addison-Wesley. All rights reserved

244 Reading a String of Characters
A queue can retain characters in the order in which they are typed aQueue.createQueue() while (not end of line) { Read a new character ch aQueue.enqueue(ch) } //end while Once the characters are in a queue, the system can process them as necessary © 2005 Pearson Addison-Wesley. All rights reserved

245 Recognizing Palindromes
A palindrome A string of characters that reads the same from left to right as its does from right to left To recognize a palindrome, a queue can be used in conjunction with a stack A stack reverses the order of occurrences A queue preserves the order of occurrences © 2005 Pearson Addison-Wesley. All rights reserved

246 Recognizing Palindromes
A nonrecursive recognition algorithm for palindromes As you traverse the character string from left to right, insert each character into both a queue and a stack Compare the characters at the front of the queue and the top of the stack © 2005 Pearson Addison-Wesley. All rights reserved

247 Recognizing Palindromes
Figure 7.3 The results of inserting a string into both a queue and a stack © 2005 Pearson Addison-Wesley. All rights reserved

248 Implementations of the ADT Queue
An array-based implementation Possible implementations of a pointer-based queue A linear linked list with two external references A reference to the front A reference to the back A circular linked list with one external reference © 2005 Pearson Addison-Wesley. All rights reserved

249 A Pointer-Based Implementation
Figure 7.4 A pointer-based implementation of a queue: (a) a linear linked list with two external pointers b) a circular linear linked list with one external pointer © 2005 Pearson Addison-Wesley. All rights reserved

250 A Pointer-Based Implementation
Figure 7.5 Inserting an item into a nonempty queue Figure 7.6 Inserting an item into an empty queue: a) before insertion; b) after insertion Figure 7.7 Deleting an item from a queue of more than one item © 2005 Pearson Addison-Wesley. All rights reserved

251 An Array-Based Implementation
Figure 7.8 a) A naive array-based implementation of a queue; b) rightward drift can cause the queue to appear full © 2005 Pearson Addison-Wesley. All rights reserved

252 An Array-Based Implementation
A circular array eliminates the problem of rightward drift A problem with the circular array implementation front and back cannot be used to distinguish between queue-full and queue-empty conditions © 2005 Pearson Addison-Wesley. All rights reserved

253 An Array-Based Implementation
Figure 7.11b (a) front passes back when the queue becomes empty; (b) back catches up to front when the queue becomes full © 2005 Pearson Addison-Wesley. All rights reserved

254 An Array-Based Implementation
To detect queue-full and queue-empty conditions Keep a count of the queue items To initialize the queue, set front to 0 back to MAX_QUEUE – 1 count to 0 © 2005 Pearson Addison-Wesley. All rights reserved

255 An Array-Based Implementation
Inserting into a queue back = (back+1) % MAX_QUEUE; items[back] = newItem; ++count; Deleting from a queue front = (front+1) % MAX_QUEUE; --count; © 2005 Pearson Addison-Wesley. All rights reserved

256 An Array-Based Implementation
Variations of the array-based implementation Use a flag isFull to distinguish between the full and empty conditions Declare MAX_QUEUE + 1 locations for the array items, but use only MAX_QUEUE of them for queue items © 2005 Pearson Addison-Wesley. All rights reserved

257 An Array-Based Implementation
Figure 7.12 A more efficient circular implementation: a) a full queue; b) an empty queue © 2005 Pearson Addison-Wesley. All rights reserved

258 An Implementation That Uses the ADT List
If the item in position 1 of a list aList represents the front of the queue, the following implementations can be used dequeue() aList.remove(1) getFront(queueFront) aList.retrieve(1, queueFront) © 2005 Pearson Addison-Wesley. All rights reserved

259 An Implementation That Uses the ADT List
If the item at the end of the list represents the back of the queue, the following implementations can be used enqueue(newItem) aList.insert(getLength() + 1, newItem) © 2005 Pearson Addison-Wesley. All rights reserved

260 The Standard Template Library Class queue
Some operations in the STL queue Dequeue and enqueue operations are called push and pop, as in a stack The back function returns a reference to the last item The size function returns the number of items An adaptor container Implemented using a more basic container type The default queue container class is deque © 2005 Pearson Addison-Wesley. All rights reserved

261 Comparing Implementations
Fixed size versus dynamic size A statically allocated array Prevents the enqueue operation from adding an item to the queue if the array is full A resizable array or a reference-based implementation Does not impose this restriction on the enqueue operation © 2005 Pearson Addison-Wesley. All rights reserved

262 Comparing Implementations
Pointer-based implementations A linked list implementation More efficient The ADT list implementation Simpler to write © 2005 Pearson Addison-Wesley. All rights reserved

263 A Summary of Position-Oriented ADTs
List Stack Queue Stacks and queues Only the end positions can be accessed Lists All positions can be accessed © 2005 Pearson Addison-Wesley. All rights reserved

264 A Summary of Position-Oriented ADTs
Stacks and queues are very similar Operations of stacks and queues can be paired off as createStack and createQueue Stack isEmpty and queue isEmpty push and enqueue pop and dequeue Stack getTop and queue getFront © 2005 Pearson Addison-Wesley. All rights reserved

265 A Summary of Position-Oriented ADTs
ADT list operations generalize stack and queue operations getLength insert remove retrieve © 2005 Pearson Addison-Wesley. All rights reserved

266 Application: Simulation
A technique for modeling the behavior of both natural and human-made systems Goal Generate statistics that summarize the performance of an existing system Predict the performance of a proposed system Example A simulation of the behavior of a bank © 2005 Pearson Addison-Wesley. All rights reserved

267 Application: Simulation
Figure A bank line at time a) 0; b) 12 c) 20; d) 38 © 2005 Pearson Addison-Wesley. All rights reserved

268 Application: Simulation
An event-driven simulation Simulated time is advanced to time of the next event Events are generated by a mathematical model that is based on statistics and probability © 2005 Pearson Addison-Wesley. All rights reserved

269 Application: Simulation
A time-driven simulation Simulated time is advanced by a single time unit The time of an event is determined randomly and compared with a simulated clock © 2005 Pearson Addison-Wesley. All rights reserved

270 Application: Simulation
The bank simulation is concerned with Arrival events External events: the input file specifies the times at which the arrival events occur Departure events Internal events: the simulation determines the times at which the departure events occur © 2005 Pearson Addison-Wesley. All rights reserved

271 Application: Simulation
An event list is needed to implement an event-driven simulation An event list Keeps track of arrival and departure events that will occur but have not occurred yet Contains at most one arrival event and one departure event © 2005 Pearson Addison-Wesley. All rights reserved

272 Summary The definition of the queue operations gives the ADT queue first-in, first-out (FIFO) behavior A pointer-based implementation of a queue uses either A circular linked list A linear linked list with a head reference and a tail reference © 2005 Pearson Addison-Wesley. All rights reserved

273 Summary A circular array eliminates the problem of rightward drift in an array-based implementation Distinguishing between the queue-full and queue-empty conditions in a circular array Count the number of items in the queue Use a isFull flag Leave one array location empty © 2005 Pearson Addison-Wesley. All rights reserved

274 Summary Simulations In a time-driven simulation
Time is advanced by a single time unit In an event-driven simulation Time is advanced to the time of the next event To implement an event-driven simulation, you maintain an event list that contains events that have not yet occurred © 2005 Pearson Addison-Wesley. All rights reserved


Download ppt "Principles of Programming and Software Engineering"

Similar presentations


Ads by Google