Copyright  1997 Oxford University Press All Rights Reserved

Slides:



Advertisements
Similar presentations
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Advertisements

C++ fundamentals.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Object Oriented Data Structures
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Rossella Lau Lecture 1, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 1: Introduction What this course is about:
Pointers OVERVIEW.
C++ Functions. Objectives 1. Be able to implement C++ functions 2. Be able to share data among functions 2.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.
Data Structures: CSCI Chapter 1 Data Structures: CSCI Chapter 1 lecture notes adapted from Data Structures with C++ using STL Dr. Nazli Mollah.
CS Class 19 Today  Practice with classes Announcements  Turn in algorithm for Project 5 in class today  Project 5 due 11/11 by midnight – .
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
1 Introduction 1. Why Data Structures? 2. What AreData Structure? 3. Phases of Software Development 4. Precondition and Postcondition 5. Examples.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Chapter 4 Abstract Data Types, Classes and Objects.
Prof. I. J. Chung Data Structure #1 Professor I. J. Chung.
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output Samples.
Lecture 3: Getting Started & Input / Output (I/O)
Chapter 15 - C++ As A "Better C"
Bill Tucker Austin Community College COSC 1315
Chapter 12 Classes and Abstraction
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Basic concepts of C++ Presented by Prof. Satyajit De
Chapter 1.2 Introduction to C++ Programming
Chapter 2: Basic Elements of C++
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 5 Functions for All Subtasks 1
Chapter 1.2 Introduction to C++ Programming
Andy Wang Object Oriented Programming in C++ COP 3330
Basic Elements of C++.
Introduction to C++ Introduced by Bjarne Stroustrup of AT&T’s Bell Laboratories in mid-1980’s Based on C C++ extended C to support object-oriented programming.
The Selection Structure
About the Presentations
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
– Introduction to Object Technology
Chapter 2 part #3 C++ Input / Output
Classes and Objects 2nd Lecture
Basic Elements of C++ Chapter 2.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Classes and Data Abstraction
Introduction to C++ Programming
Programming Funamental slides
Introduction to C++ Introduced by Bjarne Stroustrup of AT&T’s Bell Laboratories in mid-1980’s Based on C C++ extended C to support object-oriented programming.
Wednesday 09/23/13.
No I/O is built into C++ instead, a library provides input stream and output stream Keyboard Screen executing program istream ostream 1.
Chapter 3 Input output.
Friends, Overloaded Operators, and Arrays in Classes
CS150 Introduction to Computer Science 1
Introduction to Data Structure
C++ Programming Lecture 3 C++ Basics – Part I
Programs written in C and C++ can run on many different computers
Engineering Problem Solving with C++ An Object Based Approach
Engineering Problem Solving with C++ An Object Based Approach
Chapter 2 part #3 C++ Input / Output
Today’s Objectives 28-Jun-2006 Announcements
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Copyright  1997 Oxford University Press All Rights Reserved
Chapter 1 c++ structure C++ Input / Output
Introduction to Classes and Objects
Presentation transcript:

Copyright  1997 Oxford University Press All Rights Reserved Transparency Masters for Chapter 4 of Data Structures via C++ Objects by Evolution A. Michael Berman Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Chapter 4 Abstract Data Types, Classes, and Objects Overview Abstract Data Types (ADT’s) simplify programming by hiding information. The C++ Class can implement ADT’s. The principles of Object Oriented Programming start with the ADT. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Chapter Objectives 1. To understand ADT’s, information hiding, and encapsulation. 2. To see how ADT’s aid code reuse. 3. To explain the use of C++ classes to build ADT’s. 4. To understand the role of ADT’s in Object Oriented Programming. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-1: Patient Waiting Times // cx4-1.cpp // Code Example 4-1: Patient Waiting Times #include <iostream.h> // Somehow, the type "Time" gets defined up here int main() { int numberOfVisits(0), totalWaitingTime(0); char answer; do { Time arrival, seenByDoctor; cout << "Enter arrival time:"; cin >> arrival; cout << "Enter time seen by doctor:"; 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-1: Patient Waiting Times cin >> seenByDoctor; numberOfVisits++; // assume that subtracting one Time from another yields the // difference in minutes as an int totalWaitingTime += seenByDoctor - arrival; cout << "Done? Enter 'y' to quit, anything else to continue: "; cin >> answer; } while (answer != 'y'); cout << "Number of visits: " << numberOfVisits << "\n"; cout << "Total waiting time: " << totalWaitingTime << " minutes.\n"; cout << "Average wait is " << totalWaitingTime/numberOfVisits << " minutes.\n"; return 0; } 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Sample Input and Output from Patient Waiting Times Program Enter arrival time: 12:17PM Enter time seen by doctor: 12:25PM Done? Enter 'y' to quit, anything else to continue: . Enter arrival time: 1:10PM Enter time seen by doctor: 2:02PM Done? Enter 'y' to quit, anything else to continue: y Number of visits: 2 Total waiting time: 60 minutes. Average wait is 30 minutes. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercises 4-1 List six operations you would like a Time ADT to provide to you. 4-2 List three different ways you could store a representation of the time of day. What would be the relative advantages of your representations? 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Goal for Specifying Data abstract safe modifiable reusable 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Definition 4-1: Abstract Data Type An Abstract Data Type, or ADT, is a well- specified collection of data and a group of operations that can be performed upon the data. The ADT’s specification describes what data can be stored (the characteristics of the ADT), and how it can be used (the operations), but not how it is implemented or represented in the program. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved ADT 4-1: Time (part 1 of 3) Characteristics: A Time consists of some number of hours and minutes, and is either before noon (AM) or after noon (PM). Twelve Noon is 12:00 PM and Twelve Midnight is 12:00 AM. All Times are assumed to fall on the same day. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved ADT 4-1: Time (Part 2 of 3) Operations: Time readTime(bool & errorFlag) Precondition: Standard Input has characters available. Postconditions: Leading whitespace characters are ignored; readTime attempts to read, from standard input, a time in the format <HH>:<MM>:<A>, where <HH> is an integer between 1 and 12, <MM> is an integer between 0 and 59, and <A> is either “AM” or “PM”. If a properly formatted time can be read, errorFlag is set to false; otherwise, errorFlag is set to true. Returns: If errorFlag is false, the Time read from Standard Input; otherwise, an arbitrary time is returned. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved ADT 4-1: Time (Part 3 of 3) int subtractTimes(Time t1, Time t2) Precondition: t1, t2 are well-defined. Postcondition: None. Returns: The difference, in minutes, between Time t1 and Time t2. If t1 occurs before t2, this difference is negative. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 4-2: Patient waiting time program, revised for our implementation of Time // cx4-2.cpp // Code Example 4-2: Revised Patient Waiting Time Program #include "dslib.h" #include <iostream.h> // Somehow, the type "Time" gets defined up here int main() { int numberOfVisits(0), totalWaitingTime(0); char answer; do { bool errorFlag; Time arrival, seenByDoctor; cout << "Enter arrival time:"; arrival = readTime(errorFlag); 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 4-2: Patient waiting time program, revised for our implementation of Time while (errorFlag) { cout << "Arrival time was incorrectly formatted; try again: "; arrival = readTime(errorFlag); } cout << "Enter time seen by doctor:"; seenByDoctor = readTime(errorFlag); cout << "Seen by doctor time was incorrectly formatted; try again: "; 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 4-2: Patient waiting time program, revised for our implementation of Time numberOfVisits++; // assume that subtracting one Time from another yields the // difference in minutes as an int totalWaitingTime += subtractTimes(seenByDoctor, arrival); cout << "Done? Enter 'y' to quit, anything else to continue: "; cin >> answer; } while (answer != 'y'); cout << "Number of visits: " << numberOfVisits << "\n"; cout << "Total waiting time: "<< totalWaitingTime << " minutes.\n"; cout << "Average wait is " << totalWaitingTime/numberOfVisits << " minutes.\n"; return 0; } 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercises 4-3 To ADT 4-1, add definitions of operations that will add an int (representing some number of minutes) to a time, and print times out. Specify preconditions, postconditions, and return values. 4-4 Propose two different methods of representing a time, consistent with ADT 4-1. Will it be easier to implement the ADT with one representation than with the other? 4-5 Define an ADT USDollars, that can be used to represent money values represented as dollars and cents. Can you see any advantages to such an ADT over using ints or floats? 4-6 Define an ADT Zip9 that can store a 9 digit zip code. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercises 4-7 Define an ADT SSN that can store a U.S. Social Security Number. 4-8 Define an ADT TelephoneNumber, that can store a telephone number including the Area Code. 4-9 Define an ADT Date, that can represent a date between January 1, 1901 and December 31, 2099. 4-10 Define an ADT VideoTape, that can store the attributes of a video tape from the video rental system described in Chapter 2. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercise 4-11 As we approach the year 2000, there’s a crisis in certain segments of the software industry because of programs that were written using two digits for the year, e.g. 98 to represent 1998. Suppose that instead of hard-coding two digit dates into a system, it was instead designed to use a Date ADT. How might this have affected the impact of the year 2000 for these programs? 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-3: Implementation of Time ADT // cx4-3.cpp // Code Example 4-3: Implementation of Time ADT #include "dslib.h" typedef int Time; Time readTime(bool & errorFlag) { // The time must be formatted as <HH>:<MM><AMorPM>, where // <HH> is an int in the range 0 to 12, <MM> is an int in // the range 0 to 59, and <AMorPM> is either AM or PM. enum AM_PM {AM, PM} AM_or_PM; int hour, minute; const char delimiter = ':'; 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-3: Implementation of Time ADT // Assume that the format is bad -- once valid data is extracted, // reset errorFlag to false errorFlag = true; // formatted input -- fail if not an int if (!(cin >> hour)) return 0; if (hour < 0 || hour > 12) char c; cin >> c; if (c != delimiter) if (!(cin >> minute)) // formatted input 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-3: Implementation of Time ADT if (minute < 0 || minute > 59) return 0; cin >> c; if (c == 'A' || c == 'a') AM_or_PM = AM; else if (c == 'P' || c == 'p') AM_or_PM = PM; else if (c != 'M' && c != 'm') // if the program gets here, the data was correctly formatted -- // so compute the time. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-3: Implementation of Time ADT errorFlag = false; Time returnTime; if (hour == 12) returnTime = minute; else returnTime = hour*60 + minute; if (AM_or_PM == PM) returnTime += 60*12; return returnTime; } int subtractTimes(Time t1, Time t2) { return t1 - t2; 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercises 4-12 Write a test plan for the Time ADT, and test the ADT thoroughly using a driver. 4-13 Implement the additional operations specified by Exercise 4-3. 4-14 Implement the ADT USDollars defined in Exercise 4-5. 4-15 Implement the ADT Zip9 defined in Exercise 4-6. 4-16 Implement the ADT SSN defined in Exercise 4-7. 4-17 Implement the ADT TelephoneNumber defined in Exercise 4-8. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Definition 4-2 The program that uses an ADT is referred to as a client of that ADT. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Figure 4-1: Two Views of an ADT, using Time ADT as an example int minutes Time ADT Implementor’s View readTime subtractTimes Client’s View (implementation details visible here) (only the operations visible here) 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Definition 4-3 The principle that a client can use an ADT with no knowledge of its implementation is called Information Hiding. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Definition 4-4 When a programming language allows the creation of an ADT in which the client has no access to the underlying implementation, we say that the language supports encapsulation. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-4: A class declaration for the Time ADT // cx4-4.h // Code Example 4-4: Definition of Time Class #include "dslib.h" class Time { public: void readTime(bool & errorFlag); int subtractTimes(Time t); private: int minutes; }; 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-5: Full definition file for Time ADT // cx4-5.h // Code Example 4-5: full definition of class Time #include "dslib.h" // standard header file for this book class Time { // // Characteristics: // A Time consists of some number of hours and minutes, and is either before noon // (AM) or after noon (PM). // Twelve Noon is 12:00 PM and Twelve Midnight is 12:00 AM. // All Times are assumed to fall on the same day. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-5: Full definition file for Time ADT public: void readTime(bool & errorFlag); // Precondition: Standard input has characters available. // Postconditions: Leading whitespace characters are ignored; // readTime attempts to read, from standard input, a time in // the format <HH>:<MM><A>, where <HH> is an integer between // 1 and 12, <MM> is an integer between 0 and 59, and <A> is // either "AM" or "PM". If a properly formatted time can be // read, errorFlag is set to false, and the value of the Time // variable is set to the time read; otherwise, errorFlag is // set to true. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-5: Full definition file for Time ADT int subtractTimes(Time t); // Precondition: This Time variable contains a proper value. // Postcondition: None. // Returns: The difference, in minutes, between this Time and Time t. // If this Time occurs prior to Time t, the returned difference // is negative. // **** the rest of the class declaration is private private: int minutes; }; 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

ADT 4-2: Time ADT revised consistent with Class syntax (Part 1 of 3) Characteristics: A Time consists of some number of hours and minutes, and is either before noon (AM) or after noon (PM). Twelve Noon is 12:00 PM and Twelve Midnight is 12:00 AM. All Times are assumed to fall on the same day. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

ADT 4-2: Time ADT revised consistent with Class syntax (Part 2 of 3) Operations void readTime(bool & errorFlag) Precondition: Standard Input has characters available. Postconditions: Leading whitespace characters are ignored; readTime attempts to read, from standard input, a time in the format <HH>:<MM><A>, where <HH> is an integer between 1 and 12, <MM> is an integer between 0 and 59, and <A> is either “AM” or “PM”. If a properly formatted time can be read, errorFlag is set to false; otherwise, errorFlag is set to true. Returns: If errorFlag is false, the value of this Time is the time read from Standard Input; otherwise, the value of this Time remains unchanged. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

ADT 4-2: Time ADT revised consistent with Class syntax (Part 3 of 3) int subtractTimes(Time t1) Precondition: t1 is well-defined. Postcondition: None. Returns: The difference, in minutes, between this Time and Time t1; that is, this Time - t1. If this Time occurs before Time t1, this difference is negative. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 4-6: Patient Waiting Times program, revised for C++ Class notation // cx4-6.cpp // Patient Waiting Times program, revised for C++ Class notation #include <iostream.h> #include "cx4-5.h" int main() { int numberOfVisits(0), totalWaitingTime(0); char answer; do { bool errorFlag; // arrival, seenByDoctor are instances of Time class Time arrival, seenByDoctor; cout << "Enter arrival time:"; arrival.readTime(errorFlag); 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 4-6: Patient Waiting Times program, revised for C++ Class notation while (errorFlag) { cout << "Arrival time was incorrectly formatted; try again: "; arrival.readTime(errorFlag); } cout << "Enter time seen by doctor:"; seenByDoctor.readTime(errorFlag); cout << "Seen by doctor time was incorrectly formatted; try again: "; numberOfVisits++; 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 4-6: Patient Waiting Times program, revised for C++ Class notation // assume that subtracting one Time from another yields the // difference in minutes as an int totalWaitingTime += seenByDoctor.subtractTimes(arrival); cout << "Done? Enter 'y' to quit, anything else to continue: "; cin >> answer; } while (answer != 'y'); cout << "Number of visits: " << numberOfVisits << "\n"; cout << "Total waiting time: "<< totalWaitingTime << " minutes.\n"; cout << "Average wait is " << totalWaitingTime/numberOfVisits << " minutes.\n"; return 0; } 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-7: Implementation of the Time Class // cx4-7.cpp // Code Example 4-7: Implementation of the Time Class #include "cx4-5.h" void Time::readTime(bool & errorFlag) { // The time must be formatted as <HH>:<MM><AMorPM>, where // <HH> is an int in the range 0 to 12, <MM> is an int in // the range 0 to 59, and <AMorPM> is either AM or PM. enum AM_PM {AM, PM} AM_or_PM; int hour, minute; const char delimiter = ':'; // Assume that the format is bad -- once valid data is extracted, // reset errorFlag to false 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-7: Implementation of the Time Class errorFlag = true; // formatted input -- fail if not an int if (!(cin >> hour)) return; if (hour < 0 || hour > 12) char c; cin >> c; if (c != delimiter) if (!(cin >> minute)) // formatted input if (minute < 0 || minute > 59) 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-7: Implementation of the Time Class cin >> c; if (c == 'A' || c == 'a') AM_or_PM = AM; else if (c == 'P' || c == 'p') AM_or_PM = PM; else return; if (c != 'M' && c != 'm') errorFlag = false; 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-7: Implementation of the Time Class if (hour == 12) minutes = minute; else minutes = hour*60 + minute; if (AM_or_PM == PM) minutes += 60*12; } int Time::subtractTimes(Time t) { return minutes - t.minutes; 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercises 4-18 Reimplement the ADT USDollars from Exercise 4-14, using C++ class syntax. 4-19 Reimplement the ADT Zip9 from Exercise 4-15, using C++ class syntax. 4-20 Reimplement the ADT SSN from Exercise 4-16, using C++ class syntax. 4-21 Reimplement the ADT TelephoneNumber from Exercise 4-17, using C++ class syntax 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Some libraries included in the C++ Standard Libraries for handling input and output, including <iostream> (for keyboard and screen I/O) and <fstream> (for file I/O). A string manipulation library <string>. Complex numbers <complex>. Bit manipulation <bitstring>. Dynamic arrays <dynarray>. Dynamic arrays can grow and shrink during the execution of a program. The Standard Template Library <stl>, which contains implementations of many of the data structures and algorithms discussed in this book. The Standard C Libraries. Generally, you’ll want to use the newer C++ libraries wherever possible, but the C Libraries still have certain uses and also make it easier to convert old C code to C++. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-8: Using the C++ String class // cx4-8.cpp // Code Example 4-8: example client for string class // include the C++ string library. If your compiler is not compliant with the // ISO/ANSI C++ Standard, you may have to change the following line in // order to include a compatible String Class #include <string> int main() { string s1, s2, sarray[5]; string s3("xyzzy"); cout << "Enter a couple of strings... "; cin >> s1 >> s2; cout << "You entered " << s1 << " and " << s2 << ".\n"; cout << "s1 + s3 is " << (s1 + s3) << "\n"; int len = s3.length(); 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Code Example 4-8: Using the C++ String class s2 = s3.substr(1,len-2); cout << "The middle of string " << s3 << " is " << s2 << endl; cout << "Enter 5 strings for an array..."; int i; for (i = 0; i < 5; i++) cin >> sarray[i]; cout << "\nYour strings are: "; cout << sarray[i] << '\t'; s1 = sarray[0]; cout << "\ns1 is " << s1 << endl; cout << "\nResult of s1.compare(sarray[0]): " << s1.compare(sarray[0]) << endl; return 0; } 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercises 4-22 Determine which version(s) of the C++ string library you have available to you. If necessary, get an implementation from the Web page for this book or some other source. Write a program that reads in a string and processes it using several of the operations available in the string class. 4-23 Write a program that creates an array of strings, reads words into the array and sorts them. Use whatever sorting algorithm you like. Allow for up to 100 words. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Figure 4-2: Subtype relationship for rental items Video Tape Video Game Cartridge Video Disk 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Chapter Summary Abstract Data Types provide a powerful tool for organizing software. Code reuse makes programmers more efficient. Information hiding and encapsulation lead to simpler and safer software. You use a class to create an encapsulated ADT in C++. Standard C++ libraries provide an important source of reusable code. Using inheritance and polymorphism with encapsulated ADT’s is called Object-Oriented Programming. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 4-1 Write a program that prompts the user for a start time, a stop time, and a distance travelled (in miles), computes the speed in miles per hour. Use the Time ADT. Output the result rounded to the nearest tenth mile. 4-2 Write a program that takes as input a list of song titles and lengths, and determines whether or not the proposed song list will fit on a 45 minute cassette tape. Allow for a 5 second gap between songs. Your output should list the songs, the time for each, and the total time required for the tape. You will need to modify the Time ADT in order to add a function that can add two times together and give a new time. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 4-3 In the children’s game “Pig Latin”, you modify words by moving any initial consonants to the end of the word and adding “ay”; if the word starts with a vowel, you just add “ay” to the end. For example, the sentence “All good programmers use objects” would be rendered in Pig Latin as “Allay oodgay ogrammerspray useay objectsay.” Write a program that reads in a sentence and converts it to Pig Latin. (Of course, you should use the strings library.) 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 4-4 Implement a simple version of the Unix utility “uniq”. uniq reads lines from standard input and outputs the same lines to standard output, except that repeated lines are omitted. For example, if the following input is read: line one line two line two line three the output should be line one line two line three 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 4-5 Design and implement (as a C++ class) a Date ADT that can represent any date between January 1, 1901 and December 31, 2099. Remember that every fourth year is a leap year that includes February 29 as a valid date (including the year 2000). Your operations should include the following: date input and output, difference between two dates (as an int representing the number of days), adding some number of days to a date giving a new date. If you think carefully about how you represent your date internally, you can save yourself a lot of work. Test your ADT thoroughly. Deliverables: A description of the Date ADT, in a format like ADT 4-1; header file date.h; implementation file date.cpp; test plan; test driver; test results. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 4-6 Using a Date ADT (either the one written in Lab 4-5, or one obtained from another source) write a program that, given any date in the range allowed by the Date ADT, determines the day of the week for that date. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 4-7 Define an ADT IntVector that can be used to store a vector (i.e. a one-dimensional array) of ints. Operations should include v.put(i,j), which puts the value j into position i in the vector (analogous to v[i] = j) and v.at(i), which returns the value located at position i. The constructor for the IntVector class should specify the number of elements to be stored in the array; you can require that it be less than or equal to 100. Your vector class should perform range checking; that is, if the first argument to put or at is not between 0 and one less than the size of the array, an error message should be printed and the value 0 returned. (If you know how to throw exceptions in C++, you can do that instead.) Deliverables: intvect.h, intvect.cpp, test plan, test driver, test results. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 4-8 Modify the ADT IntVector class described in Lab 4-7 so that the constructor can specify starting and ending bounds of the array. For example, the line IntVector v(10, 20); would specify an array of length 11, indexed from 10 to 20. Negative bounds are allowed, but the first argument must be less than or equal to the second. The put and at operators must continue to assure that the argument is in the appropriate range. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 4-9 Using the specifications in Chapter 2, Section 2.2, create an ADT VideoTape that can store a representation of a video tape. Test your program by writing a program that creates an array of video tapes, lets the user add tapes to the array, and then prints out all the tapes in the array. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 4-10 Specify a USDollars ADT, including operations that: allow the client to add and subtract two USDollars objects; multiply or divide USDollars objects by doubles, e.g. compute $2.75 * 2.4 add or subtract percentages to a USDollars object, e.g. compute $9.95 + 10% of $9.95. return USDollars as a string properly formatted with a dollar sign, e.g. “$17.95” or “$1,750.00” or “($350.95)” for a negative value. (continued on next slide) 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems Note that for good precision you don’t want to implement a money ADT using floating point, because rounding may result in unpredictable results. For example, there is no exact binary representation of .01. Instead, the internal representation of the USDollars ADT should be stored as an int (or long int, depending upon your compiler) representing the number of cents for the value. Test your ADT by writing a driver that calls all the functions in your ADT. 2019-06-04 Copyright  1997 Oxford University Press All Rights Reserved