1 C++ Plus Data Structures Nell Dale Chapter 2 Data Design and Implementation Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.

Slides:



Advertisements
Similar presentations
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Advertisements

1 Techniques of Programming CSCI 131 Lecture 24 Structs.
Chapter 2 Data Design and Implementation 1. Lecture 4.
Chapter 10.
1 Chapter 12 Arrays Dale/Weems/Headington. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 Nell Dale Chapter 3 ADTs Unsorted List and Sorted List Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
1 C++ Plus Data Structures Nell Dale Chapter 2 Data Design and Implementation Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Chapter 9: Arrays and Strings
1 Lecture 29 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Chapter 9: Arrays and Strings
Chapter 8 Arrays and Strings
Dynamic Structures & Arrays.
1 Chapter 12 Arrays Dale/Weems/Headington. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument.
1 Lecture 22 Chapter 12 Arrays Dale/Weems/Headington.
Data Structures and Algorithms What The Course Is About Data structures is concerned with the representation and manipulation of data. All programs manipulate.
1 Chapter 9 Scope, Lifetime, and More on Functions.
C++ Plus Data Structures Data Design and Implementation
Chapter 2 Data Design and Implementation. Data The representation of information in a manner suitable for communication or analysis by humans or machines.
CISC Data Structures C/C++ Review Fall
1 C++ Plus Data Structures Nell Dale David Teague Chapter 2 Data Design and Implementation Slides by Sylvia Sorkin, Community College of Baltimore County.
1 Basic Concepts of Object-Oriented Design. 2 What is this Object ? There is no real answer to the question, but we ’ ll call it a “ thinking cap ”. l.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
1 Chapter 2 Data Design and Implementation. 2 Data The representation of information in a manner suitable for communication or analysis by humans or machines.
Chapter 8 Arrays and Strings
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Functions Why we use functions C library functions Creating our own functions.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
CPSC 252 Concrete Data Types Page 1 Overview of Concrete Data Types There are two kinds of data types: Simple (or atomic) – represents a single data item.
1 Functions every C++ program must have a function called main program execution always begins with function main any other functions are subprograms and.
1 Chapter Structured Types, Data Abstraction and Classes Dale/Weems.
1 2 Data Design and Implementation Chapter 2 Data Design and Implementation.
1 Chapter 12-3 Arrays Dale/Weems. 2 Specification of Time class Time // “Time.h” { public : // 7 function members void Set (int hours, int minutes, int.
C++ Classes and Data Structures Jeffrey S. Childs
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
1 Chapter 11 Arrays. 2 Chapter 11 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const in Function.
1 Chapter 12 Arrays. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const in Function.
1 Arrays. 2 Chapter 12 Topics  One-Dimensional Arrays  Using const in Function Prototypes  Using an Array of struct or class Objects  Using an enum.
1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
1 Chapter 12 Arrays Dale/Weems. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const.
1 Chapter 11 Arrays. 2 Chapter 11 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const in Function.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Fall 1999CS Composite Data Types. Fall 1999CS Topics to be Covered l Abstract data types l One-dimensional arrays l Two-dimensional arrays.
Fall 2013CISC2200 Yanjun Li1 Review. Fall 2013CISC2200 Yanjun Li2 Outline Array Pointer Object-Oriented Programming.
Chapter 1 Data Abstraction: The Walls CS Data Structures Mehmet H Gunes Modified from authors’ slides.
1 Chapter 12 Arrays Dale/Weems. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const.
1 Nell Dale Lecture 3 ADTs Unsorted List and Sorted List Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
1 Chapter 12 Arrays Dale/Weems. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
1 Programming in C++ Dale/Weems/Headington Chapter 11 One-Dimensional Arrays.
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
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.
Chapter 12 Classes and Abstraction
Chapter 2 Data Design and Implementation
C++ Plus Data Structures ADTs Unsorted List and Sorted List
Dale/Weems/Headington
About the Presentations
Chapter Structured Types, Data Abstraction and Classes
Multi-Dimension Arrays
C++ Data Types Simple Structured Address Integral Floating
Classes and Data Abstraction
Presentation transcript:

1 C++ Plus Data Structures Nell Dale Chapter 2 Data Design and Implementation Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus

2 Practice Exercises l Perform “white box testing” of the following code segment: l int fruits; l cout<<“how many fruits do you have?”; l cin>>fruits; l if (fruits>10) cout<<“you have plenty of fruits”<<endl; l else cout<<“not enough fruits”<<endl; l White box testing means testing all possible branches the program can take

3 Testing l “Black Box Testing”  Does the program work? l “White Box Testing”  How does the program work?

4 Exercise on Writing Assertions l Write the precondition and postcondition for a function that returns the largest of three values passed to it. The prototype of the function is as follows: l void find_largest(int val1, int val2, int val3, int& largest);

5 Software Spec.Validation Required l In November 1999, an error led $125 million Mars probe to disaster l The spacecraft’s builder, Lockheed Martin Astronautics, submitted acceleration data in English units of pounds of force instead of the metric unit called newtons. At JPL, the numbers were entered into a computer that assumed metric measurements. l rbiter html

6

7 Data Abstraction l Separation of a data type’s logical properties from its implementation. LOGICAL PROPERTIESIMPLEMENTATION What are the possible values? How can this be done in C++? What operations will be needed? How can data types be used?

8 APPLICATION REPRESENTATION Data Encapsulation l is the separation of the representation of data from the applications that use the data at a logical level; a programming language feature that enforces information hiding. int y; y = 25;

9 Encapsulated C++ Data Type int Value range: INT_MIN.. INT_MAX Operations: + prefix - prefix + infix - infix * infix / infix % infix Relational Operators infix TYPE int (inside) Representation of int as 16 bits two’s complement + Implementation of Operations

10 Abstract Data Type (ADT) l A data type whose properties (domain and operations) are specified independently of any particular implementation.

11 l Application (or user) level: modeling real-life data in a specific context. l Logical (or ADT) level: abstract view of the domain and operations. WHAT l Implementation level: specific representation of the structure to hold the data items, and the coding for operations. HOW Data from 3 different levels

12 Viewing a library from 3 different levels l Application (or user) level: Library of Congress, or Baltimore County Public Library. l Logical (or ADT) level: domain is a collection of books; operations include: check book out, check book in, pay fine, reserve a book. l Implementation level: representation of the structure to hold the “books”, and the coding for operations.

13 Composite Data Type A composite data type is a type which l stores a collection of individual data components under one variable name, l and allows the individual data components to be accessed.

4 Basic Kinds of ADT Operations l Constructor -- creates a new instance (object) of an ADT. l Transformer -- changes the state of one or more of the data values of an instance. l Observer -- allows us to observe the state of one or more of the data values without changing them. l Iterator -- allows us to process all the components in a data structure sequentially. 14

Two Forms of Composite Data Types Components are not organized with respect to one another. The organization determines method used to access individual data components. UNSTRUCTURED STRUCTURED EXAMPLES: EXAMPLES: arrays classes and structs 15

16 C++ Built-In Data Types Composite array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double

17 Records A record is a composite data type made up of a finite collection of not necessarily homogeneous elements called members or fields. For example....year 1999.maker ‘h’ ‘o’ ‘n’ ‘d’ ‘a’ ‘\0’....price thisCar at Base Address 6000

18 struct CarType { int year ; char maker[10]; float price ; } ; CarType thisCar; //CarType variables CarType myCar;

19 Accessing struct members The member selection operator (period. ) is used between the variable name and the member identifier to access individual members of a record (struct or class) type variable. EXAMPLES myCar.year thisCar.maker[4]

20 Valid struct operations l Operations valid on an entire struct type variable: assignment to another struct variable of same type, pass as a parameter to a function (either by value or by reference), return as the value of a function.

Pass-by-value CALLING BLOCK FUNCTION CALLED sends a copy of the contents of the actual parameter SO, the actual parameter cannot be changed by the function. 21

Pass-by-reference sends the location (memory address) of the actual parameter can change value of actual parameter CALLING BLOCK FUNCTION CALLED 22

23 Using struct type Reference Parameter to change a member void AdjustForInflation(CarType& car, float perCent) // Increases price by the amount specified in perCent { car.price = car.price * perCent + car.price; } ; SAMPLE CALL AdjustForInflation(myCar, 0.03);

24 Using struct type Value Parameter to examine a member bool LateModel(CarType car, int date) // Returns true if the car’s model year is later than or // equal to date; returns false otherwise. { return ( car.year >= date ) ; } ; SAMPLE CALL if ( LateModel(myCar, 1995) ) cout << myCar.price << endl ;

25 One-Dimensional Array at the Logical Level A one-dimensional array is a structured composite data type made up of a finite, fixed size (known at compile time) collection of homogeneous (all of the same data type) elements having relative positions and to which there is direct access (any element can be accessed immediately). Array operations (creation, storing a value, retrieving a value) are performed using a declaration and indexes.

26 Implementation Example float values[5]; // assume element size is 4 bytes This ACCESSING FUNCTION gives position of values[Index] Address(Index) = BaseAddress + Index * SizeOfElement Base Address values[0] values[1] values[2] values[3] values[4] Indexes

27 One-Dimensional Arrays in C++ l The index must be of an integral type (char, short, int, long, or enum). l The index range is always 0 through the array size minus 1. l Arrays cannot be assigned, and cannot be the return type of a function.

28 Another Example char name[10]; // assume element size is 1 byte name[0] name[1] name[2] name[3] name[4]..... name[9] Base Address This ACCESSING FUNCTION gives position of name[Index] Address(Index) = BaseAddress + Index * SizeOfElement

29 Passing Arrays as Parameters l In C++, arrays are always passed by reference, and & is not used with the formal parameter type. l Whenever an array is passed as a parameter, its base address is sent to the called function.

30 const array parameter Because arrays are always passed as reference parameters, you can protect the actual parameter from unintentional changes by using const in formal parameter list and function prototype. FOR EXAMPLE... // prototype float SumValues(const float values[ ], int numOfValues );

float SumValues (const float values[ ], int numOfValues ) // Pre: values[ 0] through values[numOfValues-1] // have been assigned // Returns the sum of values[0] through // values[numOfValues-1] { float sum = 0; for ( int index = 0; index < numOfValues; index++ ) { sum += values [ index ] ; } return sum; } 31

32 Two-Dimensional Array at the Logical Level A two-dimensional array is a structured composite data type made up of a finite, fixed size collection of homogeneous elements having relative positions and to which there is direct access. Array operations (creation, storing a value, retrieving a value) are performed using a declaration and a pair of indexes (called row and column) representing the component’s position in each dimension.

33 EXAMPLE -- To keep monthly high temperatures for 50 states in a two-dimensional array. const int NUM_STATES = 50 ; const int NUM_MONTHS = 12 ; int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ; [ 0 ] [ 1 ] [ 2 ].. stateHighs [2] [7]. [ 48 ] [ 49 ] [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] row 2, col 7 might be Arizona’s high for August

34 Finding the average high temperature for Arizona int total = 0 ; int month ; int average ; for ( month = 0 ; month < NUM_MONTHS ; month ++ ) total = total + stateHighs [ 2 ] [ month ] ; average = int ( total / ) ;

35 const int NUM_STATES = 50 ; const int NUM_MONTHS = 12 ; int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ; l In memory, C++ stores arrays in row order. The first row is followed by the second row, etc. 12 highs for state 0 12 highs for state 1 etc. Alabama Alaska first row second row Base Address STORAGE... rows columns

36 Implementation Level View stateHighs[ 0 ] [ 0 ] stateHighs[ 0 ] [ 1 ] stateHighs[ 0 ] [ 2 ] stateHighs[ 0 ] [ 3 ] stateHighs[ 0 ] [ 4 ] stateHighs[ 0 ] [ 5 ] stateHighs[ 0 ] [ 6 ] stateHighs[ 0 ] [ 7 ] stateHighs[ 0 ] [ 8 ] stateHighs[ 0 ] [ 9 ] stateHighs[ 0 ] [10 ] stateHighs[ 0 ] [11 ] stateHighs[ 1 ] [ 0 ] stateHighs[ 1 ] [ 1 ] stateHighs[ 1 ] [ 2 ] stateHighs[ 1 ] [ 3 ]. To locate an element such as stateHighs [ 2 ] [ 7] the compiler needs to know that there are 12 columns in this two-dimensional array. At what address will stateHighs [ 2 ] [ 7 ] be found? Assume 2 bytes for type int. Base Address 8000

37 Two-Dimensional Array Parameters l Just as with a one-dimensional array, when a two- (or higher) dimensional array is passed as a parameter, the base address of the actual array is sent to the function. l The size of all dimensions except the first must be included in the function heading and prototype. l The sizes of those dimensions for the formal parameter must be exactly the same as in the actual array.

38 const int NUM_STATES = 50 ; const int NUM_MONTHS = 12 ; int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ; int stateAverages [ NUM_STATES ] ; [ 0 ] ? [ 1 ] ? [ 2 ]. [ 48 ] [ 49 ] [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] Use the two-dimensional stateHighs array to fill a one-dimensional stateAverages array Alaska Arizona

void findAverages ( const int stateHighs [ ] [ NUM_MONTHS], int stateAverages [ ] ) // Pre: stateHighs[ 0..NUM_STATES-1] [ 0..NUM_MONTHS-1] assigned // Post: stateAverages[ 0..NUM_STATES-1 ] contains rounded average // high temperature for each state { int state; int month; int total; for ( state = 0 ; state < NUM_STATES; state++ ) { total = 0 ; for ( month = 0 ; month < NUM_MONTHS ; month++ ) total += stateHighs [ state ] [ month ] ; stateAverages [ state ] = int ( total / ) ; } 39

40 Using typedef with arrays helps eliminate the chances of size mismatches between formal and actual parameters. FOR EXAMPLE, typedef int StateHighsType [ NUM_STATES ] [ NUM_MONTHS ] ; typedef int StateAveragesType [ NUM_STATES ] ; void findAverages( const StateHighsType stateHighs, StateAveragesType stateAverages ) {. } 40

41 Declaring Multidimensional Arrays EXAMPLE USING TYPEDEF const int NUM_DEPTS = 5 ; // mens, womens, childrens, electronics, linens const int NUM_MONTHS = 12 ; const int NUM_STORES = 3 ; // White Marsh, Owings Mills, Towson typedef long MonthlySalesType [NUM_DEPTS] [NUM_MONTHS] [NUM_STORES]; MonthlySalesType monthlySales;

const int NUM_DEPTS = 5 ; // mens, womens, childrens, electronics, linens const int NUM_MONTHS = 12 ; const int NUM_STORES = 3 ; // White Marsh, Owings Mills, Towson typedef long MonthlySalesType [NUM_DEPTS] [NUM_MONTHS] [NUM_STORES] ; MonthlySalesType monthlySales; monthlySales [ 3 ][ 7 ][ 0 ] sales for electronics in August at White Marsh 12 MONTHS columns 5 DEPTS rows 3 STORES sheets 42

43 C++ class data type l A class is an unstructured type that encapsulates a fixed number of data components (data members) with the functions (called member functions) that manipulate them. l The predefined operations on an instance of a class are whole assignment and component access.

44 class DateType Specification // SPECIFICATION FILE( datetype.h ) class DateType// declares a class data type { public : // 4 public member functions void Initialize ( int newMonth, int newDay, int newYear ) ; int YearIs( ) const ; // returns year int MonthIs( ) const ; // returns month int DayIs( ) const ; // returns day private :// 3 private data members int year ; int month ; int day ; } ; 44

45 Use of C++ data type class l Variables of a class type are called objects (or instances) of that particular class. l Software that declares and uses objects of the class is called a client. l Client code uses public member functions (called methods in OOP) to handle its class objects. l Sending a message means calling a public member function.

46 Client Code Using DateType #include “datetype.h” // includes specification of the class #include “bool.h” int main ( void ) { DateType startDate ; // declares 2 objects of DateType DateType endDate ; bool retired = false ; startDate.Initialize ( 6, 30, 1998 ) ; endDate.Initialize ( 10, 31, 2002 ) ; cout << startDate.MonthIs( ) << “/” << startDate.DayIs( ) << “/” << startDate.YearIs( ) << endl; while ( ! retired ) { finishSomeTask( ) ;... } 46

47 2 separate files generally used for class type // SPECIFICATION FILE ( datetype.h ) // Specifies the data and function members. class DateType { public:... private:... } ; // IMPLEMENTATION FILE ( datetype.cpp ) // Implements the DateType member functions....

48 DateType Class Instance Diagrams Initialize YearIs MonthIs DayIs startDate endDate Private data: year month day Initialize YearIs MonthIs DayIs Private data: year month day

49 Implementation of DateType member functions // IMPLEMENTATION FILE (datetype.cpp) #include “datetype.h” // also must appear in client code void DateType :: Initialize ( int newMonth, int newDay, int newYear ) // Post: year is set to newYear. // month is set to newMonth. // day is set to newDay. { year = newYear ; month = newMonth ; day = newDay ; } 49

int DateType :: MonthIs ( ) const // Accessor function for data member month { return month ; } int DateType :: YearIs ( ) const // Accessor function for data member year { return year ; } int DateType :: DayIs ( ) const // Accessor function for data member day { return day ; } 50

51 Familiar Class Instances and Member Functions l The member selection operator (. ) selects either data members or member functions. l Header files iostream and fstream declare the istream, ostream,and ifstream, ofstream I/O classes. l Both cin and cout are class objects and get and ignore are member functions. cin.get (someChar) ; cin.ignore (100, ‘\n’) ; l These statements declare myInfile as an instance of class ifstream and invoke member function open. ifstream myInfile ; myInfile.open ( “A:\\mydata.dat” ) ;

52 Scope Resolution Operator ( :: ) l C++ programs typically use several class types. l Different classes can have member functions with the same identifer, like Write( ). l Member selection operator is used to determine the class whose member function Write( ) is invoked. currentDate.Write( ) ;// class DateType numberZ.Write( ) ;// class ComplexNumberType l In the implementation file, the scope resolution operator is used in the heading before the member function’s name to specify its class. void DateType :: Write ( ) const {... }

53 Information Hiding Class implementation details are hidden from the client’s view. This is called information hiding. Public functions of a class provide the interface between the client code and the class objects. client code specificationimplementation abstraction barrier

// SPECIFICATION FILE( strtype.h ) #include const int MAX_CHARS = 200 ; enum RelationType { LESS, EQUAL, GREATER } ; enum InType { ALPHA_NUM, ALPHA, NON_WHITE, NOT_NEW } ; class StrType// declares class data type { public : // 7 public member functions void MakeEmpty ( ) ; void GetString ( bool skip, InType charsAllowed ) ; void GetStringFile ( bool skip, InType charsAllowed, ifstream& inFile ) ; void PrintToScreen ( bool newLine ) const ; void PrintToFile ( bool newLine, ofstream& outFile) const ; int LengthIs( ) const ; void CopyString( StrType& newString ) const ; private :// 1 private data member char letters [MAX_CHARS + 1 ] ; } ; 54

55 StrType Class Interface Diagram StrType class Private data: letters GetString GetStringFile CopyString LengthIs PrintToFile MakeEmpty PrintToScreen ‘c’ ’a’ ’t’ ’ \0 ’...

// IMPLEMENTATION FILE (strtype.cpp) #include “strtype.h” // also appears in client code #include “string.h” void StrType :: MakeEmpty ( ) // Post: letters is empty string. { letters[0] = ‘\0’ ; }... int StrType :: LengthIs ( ) const // Returns length of letters string. { return strlen ( letters ) ; } 56

57 Handling Exceptions l In a program, we may encounter a run time error l If we abort the program, all the work done so far may be lost l The program should somehow save the work, warn the user and exit gracefully

58 Writing Exception Handling Code l Let us use try~catch and throw statements l If an exception occurs, we alert the system with “throw” statement l Then the program enters the exception handling code within the catch clause

59 An Example l #include l using namespace std; l void main() l { l double price,sum; l sum = 0.0; l try l { do { n cout<<"Enter a price (ctrl-D and ENTER to stop)"; n cin>>price; n if (price < 0) throw string("bad number "); n If (cin) sum = sum + price; n } while (cin); n }

60 Sample Code l catch (string message) l { l cout<< message << "found in the input" <<endl; l exit(0); l } l cout<<"the sum of prices entered is"<<sum<<endl; l }