1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of...

71
1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva - SUNY Fredonia

Transcript of 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of...

Page 1: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

1

C++ Plus Data Structures

Nell Dale

Lecture 2

Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus

Modified by Reneta Barneva - SUNY Fredonia

Page 2: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

2

Data Abstraction

Separation of a data type’s logical properties from its implementation.

LOGICAL PROPERTIES IMPLEMENTATION

What are the possible values? How can this be done in C++?

What operations will be needed? How can data types be used?

Page 3: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

3

APPLICATION

0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1

REPRESENTATION

Data Encapsulation

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;

Page 4: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

4

Encapsulated C++ Data Type int

Value range: INT_MIN . . INT_MAX

Operations: + prefix - prefix + infix - infix * infix / infix % infixRelational Operators infix

TYPE int

(inside)

Representation of

int

as 16 bits two’s complement

+

Implementation of Operations

Page 5: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

5

Abstract Data Type (ADT)

A data type whose properties (domain and operations) are specified independently of any particular implementation.

Page 6: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

6

Application (or user) level: modeling real-life data in a specific context.

Logical (or ADT) level: abstract view of the domain and operations. WHAT

Implementation level: specific representation of the structure to hold the data items, and the coding for operations. HOW

Data from 3 different levels

Page 7: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

7

Viewing a library from 3 different levels

Application (or user) level: Library of Congress, or Baltimore County Public Library.

Logical (or ADT) level: domain is a collection of books; operations include: check book out, check book in, pay fine, reserve a book.

Implementation level: representation of the structure to hold the “books”, and the coding for operations.

Page 8: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

8

Composite Data Type

A composite data type is a type which

stores a collection of individual data components under one variable name,

and allows the individual data components to be accessed.

Page 9: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

4 Basic Kinds of ADT Operations

Constructor -- creates a new instance (object) of an ADT.

Transformer -- changes the state of one or more of the data values of an instance.

Observer -- allows us to observe the state of one or more of the data values without changing them.

Iterator -- allows us to process all the components in a data structure sequentially.

9

Page 10: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

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: arraysclasses and structs

10

Page 11: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

11

C++ Built-In Data TypesC++ Built-In Data Types

Composite

array struct union class

Address

pointer reference

Simple

Integral Floating

char short int long enum

float double long double

Page 12: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

12

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 18678.92

thisCar at Base Address 6000

Page 13: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

13

struct CarType

struct CarType{

int year ; char maker[10];

float price ;

} ;

CarType thisCar; //CarType variables

CarType myCar;

Page 14: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

14

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]

Page 15: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

15

Valid struct operations

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.

Page 16: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

Pass-by-value

CALLINGBLOCK

FUNCTION CALLED

sends a copy of the contents of the actual parameter

SO, the actual parameter cannot be changed by the function.

16

Page 17: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

Pass-by-reference

sends the location (memory address)of the actual parameter

can change value ofactual parameter

CALLINGBLOCK FUNCTION

CALLED

17

Page 18: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

18

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);

Page 19: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

19

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 ;

Page 20: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

20

C++ class data type

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.

The predefined operations on an instance of a class are whole assignment and component access.

Page 21: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

21

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 yearint MonthIs( ) const ; // returns monthint DayIs( ) const ; // returns day

private : // 3 private data members

int year ; int month ; int day ;

} ;21

Page 22: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

22

Use of C++ data type class

Variables of a class type are called objects (or instances) of that particular class.

Software that declares and uses objects of the class is called a client.

Client code uses public member functions (called methods in OOP) to handle its class objects.

Sending a message means calling a public member function.

Page 23: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

23

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( ) ; . . . } }

23

Page 24: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

24

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.

. . .

Page 25: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

25

DateType Class Instance Diagrams

Initialize

YearIs

MonthIs

DayIs

startDate endDate

Private data:

year

month

day

2002

10

31

Initialize

YearIs

MonthIs

DayIs

1998

6

30

Private data:

year

month

day

Page 26: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

26

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 ;

}26

Page 27: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

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 ;

} 27

Page 28: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

28

Familiar Class Instances and Member Functions

The member selection operator ( . ) selects either data members or member functions.

Header files iostream.h and fstream.h declare the istream, ostream,and ifstream, ofstream I/O classes.

Both cin and cout are class objects and get and ignore

are member functions.cin.get (someChar) ;

cin.ignore (100, ‘\n’) ;

These statements declare myInfile as an instance of class ifstream and invoke member function open.

ifstream myInfile ;

myInfile.open ( “A:\\mydata.dat” ) ;

Page 29: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

29

Scope Resolution Operator ( :: ) C++ programs typically use several class types.

Different classes can have member functions with the same identifer, like Write( ).

Member selection operator is used to determine the class whose member function Write( ) is invoked.

currentDate .Write( ) ; // class DateType

numberZ .Write( ) ; // class ComplexNumberType

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{ . . .

}

Page 30: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

30

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.

clientcode

specification implementation

abstraction barrier

Page 31: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

// SPECIFICATION FILE ( strtype.h )#include <fstream.h>#include <iostream.h>

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 memberchar letters [MAX_CHARS + 1 ] ;

} ; 31

Page 32: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

32

StrType Class Interface Diagram

StrType class

Private data:

letters

GetString

GetStringFile

CopyString

LengthIs

PrintToFile

MakeEmpty

PrintToScreen‘c’ ’a’ ’t’ ’\0’ ...

Page 33: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

33

Multifile C++ Programs

C++ programs often consist of several different files with extensions such as .h and .cpp

related typedef statements, const values, enum type declarations, and similar items are often placed in user-written header files

by using the #include preprocessor directive the contents of these header files are inserted into any program file that uses them

Page 34: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

34

Inserting Header Files

#include <iostream> // iostream

#include “school.h”

int main ( )

{ enum SchoolType

{ PRE_SCHOOL,

. ELEM_SCHOOL, .

MIDDLE_SCHOOL,. HIGH_SCHOOL, COLLEGE } ;

}

Page 35: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

// 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 ) ;

} 35

Page 36: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

36

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.

Page 37: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

37

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]

7000 7004 7008 7012 7016

Indexes

Page 38: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

38

One-Dimensional Arrays in C++

The index must be of an integral type (char, short, int, long, or enum).

The index range is always 0 through the array size minus 1.

Arrays cannot be assigned, and cannot be the return type of a function.

Page 39: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

39

Another Example

char name[10]; // assume element size is 1 byte

name[0] name[1] name[2] name[3] name[4] . . . . . name[9]

6000 6001 6002 6003 6004 6005 6006 6007 6008 6009

Base Address

This ACCESSING FUNCTION gives position of name[Index]

Address(Index) = BaseAddress + Index * SizeOfElement

Page 40: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

40

Passing Arrays as Parameters

In C++, arrays are always passed by reference, and & is not used with the formal parameter type.

Whenever an array is passed as a parameter, its base address is sent to the called function.

Page 41: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

41

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 );

Page 42: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

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;

}

42

Page 43: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

43

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.

Page 44: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

44

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]

66 64 72 78 85 90 99 115 98 90 88 80row 2,col 7might beArizona’shigh forAugust

Page 45: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

45

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 / 12.0 + 0.5 ) ;

Page 46: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

46

const int NUM_STATES = 50 ;const int NUM_MONTHS = 12 ;int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ;

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

8000 8024 8048

Base Address

STORAGE

. . .

rows columns

Page 47: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

47

Implementation Level ViewstateHighs[ 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 asstateHighs [ 2 ] [ 7] the compiler needs to know that there are 12 columnsin this two-dimensional array.

At what address will stateHighs [ 2 ] [ 7 ] be found?

Assume 2 bytes for type int.

Base Address 8000

Page 48: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

48

Two-Dimensional Array Parameters

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.

The size of all dimensions except the first must be included in the function heading and prototype.

The sizes of those dimensions for the formal parameter must be exactly the same as in the actual array.

Page 49: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

49

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]

43 42 50 55 60 78 79 80 77 72 63 4066 64 72 78 85 90 99 115 98 90 88 80

Use the two-dimensional stateHighs array to fill a one-dimensional stateAverages array

Alaska

Arizona

Page 50: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

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 / 12.0 + 0.5 ) ; }

}50

Page 51: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

51

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 )

{ . . .

}51

Page 52: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

52

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;

Page 53: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

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 D

EP

TS

ro

ws

3 STORES

sheets

53

Page 54: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

54

More about Array Index

array index can be any integral type. This includes char and enum types

it is programmer’s responsibility to make sure that an array index does not go out of bounds. The index must be within the range 0 through the declared array size minus one

using an index value outside this range causes the program to access memory locations outside the array. The index value determines which memory location is used

Page 55: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

55

Enumeration Types

C++ allows creation of a new simple type by listing (enumerating) all the ordered values in the domain of the type

EXAMPLE

enum MonthType { JAN, FEB, MAR, APR, MAY, JUN,

JUL, AUG, SEP, OCT, NOV, DEC } ;

name of new type list of all possible values of this new type

Page 56: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

56

enum Type Declaration

enum MonthType { JAN, FEB, MAR, APR, MAY, JUN,

JUL, AUG, SEP, OCT, NOV, DEC } ;

the enum declaration creates a new programmer-defined type and lists all the possible values of that type--any valid C++ identifiers can be used as values

the listed values are ordered as listed. That is, JAN < FEB < MAR < APR , and so on

you must still declare variables of this type

Page 57: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

57

Declaring enum Type Variables

enum MonthType { JAN, FEB, MAR, APR, MAY, JUN,

JUL, AUG, SEP, OCT, NOV, DEC } ;

MonthType thisMonth; // declares 2 variables

MonthType lastMonth; // of type MonthType

lastMonth = OCT ; // assigns values

thisMonth = NOV ; // to these variables...

lastMonth = thisMonth ;

thisMonth = DEC ;

Page 58: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

58

Storage of enum Type Variables

enum MonthType { JAN, FEB, MAR, APR, MAY, JUN,

JUL, AUG, SEP, OCT, NOV, DEC } ;

stored as 0 stored as 1 stored as 2 stored as 3 etc.

stored as 11

Page 59: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

59

Use Type Cast to Incrementenum Type Variables

enum MonthType { JAN, FEB, MAR, APR, MAY, JUN,

JUL, AUG, SEP, OCT, NOV, DEC } ;

MonthType thisMonth;

MonthType lastMonth;

lastMonth = OCT ;

thisMonth = NOV ;

lastMonth = thisMonth ;

thisMonth = thisMonth++ ; // COMPILE ERROR !

thisMonth = MonthType( thisMonth + 1) ; // uses type cast

Page 60: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

60

More about enum Type

Enumeration type can be used in a Switch statement for the switch expression and the case labels.

Stream I/O ( using the insertion << and extraction >> operators ) is not defined for enumeration types. Instead, functions can be written for this purpose.

Comparison of enum type values is defined using the 6 relational operators ( < , <= , > , >= , == , != ).

An enum type can be the return type of a value-returning function in C++.

SOME EXAMPLES . . .

Page 61: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

61

MonthType thisMonth;

switch ( thisMonth ) // using enum type switch expression

{

case JAN :

case FEB :

case MAR : cout << “Winter quarter” ;

break ;

case APR :

case MAY :

case JUN : cout << “Spring quarter” ;

break ;

case JUL :

case AUG :

case SEP : cout << “Summer quarter” ;

break ;

case OCT :

case NOV :

case DEC : cout << “Fall quarter” ;

}

Page 62: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

62

Using enum type Control Variable with for Loop

enum MonthType { JAN, FEB, MAR, APR, MAY, JUN,

JUL, AUG, SEP, OCT, NOV, DEC } ;

void WriteOutName ( /* in */ MonthType ) ; // prototype.. .

MonthType month ;

for (month = JAN ; month <= DEC ; month = MonthType (month + 1 ) )

{ // requires use of type cast to increment

WriteOutName ( month ) ; // function call to perform output ...

}

Page 63: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

63

void WriteOutName ( /* in */ MonthType month )// Prints out calendar name corresponding to month// Precondition: month is assigned// Postcondition: calendar name for month has been written out

{ switch ( month )

{

case JAN : cout << “ January ” ; break ;

case FEB : cout << “ February ” ; break ;

case MAR : cout << “ March ” ; break ;

case APR : cout << “ April ” ; break ;

case MAY : cout << “ May ” ; break ;

case JUN : cout << “ June ” ; break ;

case JUL : cout << “ July ” ; break ;

case AUG : cout << “ August ” ; break ;

case SEP : cout << “ September ” ; break ;

case OCT : cout << “ October ” ; break ;

case NOV : cout << “ November ” ; break ;

case DEC : cout << “ December ” ; break ;

}

}

Page 64: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

64

enum SchoolType { PRE_SCHOOL, ELEM_SCHOOL, MIDDLE_SCHOOL, HIGH_SCHOOL, COLLEGE } ;

.

.

.

SchoolType GetSchoolData ( void )

// Obtains information from keyboard to determine school level// Postcondition: Function value == personal school level{

SchoolType schoolLevel ;

int age ;

int lastGrade ;

cout << “Enter age : “ ; // prompt for information

cin >> age ;

Function with enum type Return Value

Page 65: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

65

if ( age < 6 )

schoolLevel = PRE_SCHOOL ;

else

{ cout << “Enter last grade completed in school : “ ;

cin >> lastGrade;

if ( lastGrade < 5 )

schoolLevel = ELEM_SCHOOL ;

else if ( lastGrade < 8 )

schoolLevel = MIDDLE_SCHOOL ;

else if ( lastGrade < 12 )

schoolLevel = HIGH_SCHOOL ;

else

schoolLevel = COLLEGE ;

}

return schoolLevel ; // return enum type value

}

Page 66: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

66

Array with enum Index Type

DECLARATIONenum Department { WOMENS, MENS, CHILDRENS,

LINENS, HOUSEWARES, ELECTRONICS };

float salesAmt [ 6 ] ;

Department which;

USEfor ( which = WOMENS ; which <= ELECTRONICS ;

which = Department ( which + 1 ) )

cout << salesAmt [ which ] << endl;

Page 67: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

67

float salesAmt[6];

salesAmt [ WOMENS ] ( i. e. salesAmt [ 0 ] )

salesAmt [ MENS] ( i. e. salesAmt [ 1 ] )

salesAmt [ CHILDRENS ] ( i. e. salesAmt [ 2 ] )

salesAmt [ LINENS ] ( i. e. salesAmt [ 3 ] )

salesAmt [ HOUSEWARES ] ( i. e. salesAmt [ 4 ] )

salesAmt [ ELECTRONICS ] ( i. e. salesAmt [ 5 ] )

Page 68: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

68

Switch Statement

Is a selection control structure for multi-way branching.

SYNTAXswitch ( IntegralExpression )

{

case Constant1 :

Statement(s); // optional

case Constant2 :

Statement(s); // optional . . .

default : // optional

Statement(s); // optional

}

Page 69: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

69

float weightInPounds = 165.8 ;char weightUnit ;

. . . // user enters letter for desired weightUnitswitch ( weightUnit ){

case ‘P’ :case ‘p’ :

cout << weightInPounds << “ pounds “ << endl ;break ;

case ‘O’ :case ‘o’ :

cout << 16.0 * weightInPounds << “ ounces “ << endl ;break ;

case ‘K’ :case ‘k’ :

cout << weightInPounds / 2.2 << “ kilos “ << endl ;break ;

case ‘G’ :case ‘g’ :

cout << 454.0 * weightInPounds << “ grams “ << endl ;break ;

default :cout << “That unit is not handled! “ << endl ;break ;

}

Page 70: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

70

Switch Statement

the value of IntegralExpression (of char, short, int, long or enum type ) determines which branch is executed

case labels are constant ( possibly named ) integral expressions. Several case labels can precede a statement

Page 71: 1 C++ Plus Data Structures Nell Dale Lecture 2 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva.

71

Control in Switch Statement control branches to the statement following the case

label that matches the value of IntegralExpression. Control proceeds through all remaining statements, including the default, unless redirected with break

if no case label matches the value of IntegralExpression, control branches to the default label, if present--otherwise control passes to the statement following the entire switch statement

forgetting to use break can cause logical errors because after a branch is taken, control proceeds sequentially until either break or the end of the switch statement occurs