Title: Composite Data Types
1Composite Data Types
2Topics to be Covered
- Abstract data types
- One-dimensional arrays
- Two-dimensional arrays
- Records
3Data Abstraction
- Separation of a data types 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?
4Data 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
5Encapsulated C Data Type int
TYPE int
Representation of int as 16 bits twos
complement Implementation of
Operations
Value range INT_MIN . . INT_MAX
Operations prefix - prefix
infix - infix infix / infix
infix Relational Operators infix
(inside)
6Abstract Data Type (ADT)
- A data type whose properties (domain and
operations) are specified independently of any
particular implementation.
7Data Structures
- A collection of data elements
- that can be decomposed into its component
elements - whose organization is a feature how each element
is accessed. - that its implementation of both organization and
accessing of data elements in an ADT
8Data from 3 different levels
- 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
9Viewing 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.
10Viewing a ATM Machine from 3 different levels
- Application (or user) level
- Logical (or ADT) level
- Implementation level
11Composite Data Type
- A composite (or structured) data type is a type
which - stores a collection of individual data components
(values) under one variable name, - and allows the individual data components to be
accessed for assignment or use.
124 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.
12
13Two Forms of Composite Data Types
STRUCTURED
The organization determines method used to
access individual data components.
Components are not organized with respect to
one another.
EXAMPLES EXAMPLES arrays classes and structs
13
14C Built-In Data Types
Simple
Composite
Integral
Floating
array struct union class
char short int long enum
float double long double
15One-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. -
16Implementation Example
This ACCESSING FUNCTION gives position of
valuesIndex Address(Index) BaseAddress
Index SizeOfElement
- float values5 // assume element size is
4 bytes
Base Address
7000 7004 7008 7012
7016
values0 values1 values2 values3
values4
Indexes
17One-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. - SYNTAX
- DataType ArrayName ConstIntExpression
18Another Example
- char name10 // assume element size is 1
byte
This ACCESSING FUNCTION gives position of
nameIndex Address(Index) BaseAddress Index
SizeOfElement
Base Address
6000 6001 6002 6003 6004 6005
6006 6007 6008 6009
name0 name1 name2 name3 name4
. . . . .
name9
19Assigning values to individual array elements
- float temps 5 // allocates memory for
array - int m 4
- temps 2 98.6
- temps 3 101.2
- temps 0 99.4
- temps m temps 3 / 2.0
- temps 1 temps 3 - 1.2 // what value
is assigned?
7000 7004 7008 7012
7016
99.4 ? 98.6 101.2
50.6
temps0 temps1 temps2 temps3
temps4
20What values are assigned?
- float temps 5 // allocates memory for
array - int m
- for (m 0 m lt 5 m)
-
- temps m 100.0 m 0.2
7000 7004 7008 7012
7016
? ? ? ?
?
temps0 temps1 temps2 temps3
temps4
21Now what values are printed?
- float temps 5 // allocates memory for
array - int m
- . . . . .
- for (m 4 m gt 0 m-- )
-
- cout ltlt temps m ltlt endl
-
7000 7004 7008 7012
7016
100.0 100.2 100.4 100.6
100.8
temps0 temps1 temps2 temps3
temps4
22Variable subscripts
- float temps 5 // allocates memory for
array - int m 3
- . . . . . .
- What is temps m 1 ?
- What is temps m 1 ?
7000 7004 7008 7012
7016
100.0 100.2 100.4 100.6
100.8
temps0 temps1 temps2 temps3
temps4
23A Closer Look at the Compiler
- float temps5 // this declaration allocates
memory - To the compiler, the value of the identifier
temps alone is the base address of the array. We
say temps is a pointer (because its value is an
address). It points to a memory location.
24Initializing in a declaration
- int ages 5 40, 13, 20, 19, 36
- for ( int m 0 m lt 5 m )
-
- cout ltlt ages m
25Passing 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.
26Passing Arrays as Parameters
- Generally, functions that work with arrays
require 2 items of information as actual
parameters - the beginning address of the array (in memory),
- and the number of elements to process in the
array.
27const 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 )
28float SumValues (const float values ,
int
numOfValues )
- // Pre values 0 through valuesnumOfValues-1
- // have been assigned
- // Returns the sum of values0 through
- // valuesnumOfValues-1
-
- float sum 0
- for ( int index 0 index lt numOfValues
index ) -
- sum values index
-
- return sum
28
29Array Index
- Array index can be any integral type. This
includes char and enum types. - It is programmers 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.
30Array with enum Index Type
- DECLARATION
- enum Department WOMENS, MENS, CHILDRENS,
LINENS, HOUSEWARES, ELECTRONICS
- float salesAmt 6
- Department which
- USE
- for ( which WOMENS which lt ELECTRONICS
- which
Department ( which 1 ) ) - cout ltlt salesAmt which ltlt endl
31 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 )
32Parallel arrays
- DEFINITION
- Parallel arrays are 2 or more arrays that have
the same index range, and whose elements contain
related information, possibly of different data
types. - EXAMPLE
- const int SIZE 50
- int idNumber SIZE
- float hourlyWage SIZE
parallel arrays
33const int SIZE 50 int idNumber SIZE
// parallel arrays holdfloat
hourlyWage SIZE // related information
idNumber 0 4562 hourlyWage 0
9.68 idNumber 1 1235
hourlyWage 1 45.75
idNumber 2 6278 hourlyWage 2
12.71 .
. .
. . .
.
. . .
.
. idNumber 48 8754 hourlyWage 48
67.96 idNumber 49 2460
hourlyWage 49 8.97
34String in C
- A string is an array of characters which contains
a non-printing null character \0 ( with
ASCII value 0 ) marking its end. -
- A string can be initialized in its declaration in
two equivalent ways. -
- char message 8 H, e, l, l,
o, \0 -
- char message 8 Hello
2
35char vs. string
- A has data type char
- and is stored in 1 byte
- A is a string of 2 characters
- and is stored in 2 bytes
-
3
36Recall that . . .
- char message8 // this declaration allocates
memory - To the compiler, the value of the identifier
message alone is the base address of the array.
We say message is a pointer (because its value is
an address). It points to a memory location.
4
37Aggregate String I/O in C
- I/O of an entire string is possible using the
array identifier with no subscripts and no
looping.
EXAMPLE char message 8 cin gtgt
message cout ltlt message HOWEVER
. . .
5
38 Extraction operator gtgt
- When using the extraction operator ( gtgt ) to
read input characters into a string variable, - the gtgt operator skips any leading whitespace
characters such as blanks and newlines. - It then reads successive characters into the
array, and stops at the first trailing whitespace
character (which is not consumed, but remains
waiting in the input stream). - The gtgt operator adds the null character to the
end of the string.
6
39Example using gtgt
- char name 5
- cin gtgt name
- Suppose input stream looks like this
- J o e
total number of elements in the array
7000
J o e \0
name 0 name 1 name 2 name 3
name 4
7
null character is added
40Function get( )
- Because the extraction operator stops reading at
the first trailing whitespace, gtgt cannot be used
to input a string with blanks in it. - If your strings declared size is not large
enough to hold the input characters and add the
\0, the extraction operator stores characters
into memory beyond the end of the array. - Use get function with 2 parameters to overcome
these obstacles. - EXAMPLE
- char message 8
- cin.get ( message, 8 ) // inputs at most 7
characters plus \0
8
41inFileStream.get ( str, count 1)
- get does not skip leading whitespace characters
such as blanks and newlines. - get reads successive characters (including
blanks) into the array, and stops when it either
has read count characters, or it reaches the
newline character \n, whichever comes first. - get appends the null character to str.
- If it is reached, newline is not consumed by get,
but remains waiting in the input stream.
9
42Function ignore( )
- can be used to consume any remaining characters
up to and including the newline \n left in the
input stream by get - EXAMPLE
- cin.get ( string1, 81 ) // inputs at most
80 characters - cin.ignore ( 30, \n ) // skips at most
30 characters // but stops if \n
is read - cin.get ( string2, 81 )
10
43Another example using get( )
- char ch
- char fullName 31
- char address 31
- cout ltlt Enter your full name
- cin.get ( fullName, 31 )
- cin.get (ch) // to
consume the newline - cout ltlt Enter your address
- cin.get ( address, 31 )
N e l l D a
l e \0 . . .
fullName 0
A u s t i n
T X \0 . . .
11
address 0
44String function prototypes inlt string.h gt
- int strlen (char str )
- // FCTNVAL integer length of string str (
not including \0 ) - int strcmp ( char str1 , char str2 )
- // FCTNVAL negative, if str1 precedes str2
lexicographically - // positive, if str1 follows str2
lexicographically - // 0, if str1 and str2 characters same
through \0 - char strcpy ( char toStr , char fromStr
) - // FCTNVAL base address of toStr ( usually
ignored ) - // POSTCONDITION characters in string fromStr
are copied to - // string toStr, up to and including \0,
- // overwriting contents of string toStr
12
45- include ltstring.hgt
- .
- .
- .
- char author 21
- int length
- cin.get ( author , 21 )
- length strlen ( author ) // What is the
value of length ?
46- char myName 21 Huang // WHAT IS
OUTPUT? - char yourName 21
- cout ltlt Enter your last name
- cin.get ( yourName, 21 )
- if ( strcmp ( myName, yourName ) 0 )
- cout ltlt We have the same name!
- else if ( strcmp ( myName, yourName ) lt 0 )
- cout ltlt myName ltlt comes before ltlt
yourName - else if ( strcmp ( myName, yourName ) gt 0 )
- cout ltlt yourName ltlt comes before ltlt
myName
H u a n g \0
. . .
myName 0
H e a d i n g t
o n \0 . . .
yourName 0
47- char myName 21 Huang
- char yourName 21
- if ( myName yourName ) // compares
addresses only! - // That is, 4000 and 6000 here.
- . // DOES NOT COMPARE CONTENTS!
- .
- .
-
4000
H u a n g \0
. . .
myName 0
6000
H e a d i n g t
o n \0 . . .
yourName 0
48- char myName 21 Huang
- char yourName 21
- cin.get ( yourName, 21 )
- yourName myName // DOES NOT COMPILE!
- // What is the value of myName ?
4000
H u a n g \0
. . .
myName 0
6000
H e a d i n g t
o n \0 . . .
yourName 0
49- char myName 21 Huang
- char yourName 21
- cin.get ( yourName, 21 )
- strcpy ( yourName, myName ) // changes
string yourName - // OVERWRITES CONTENTS!
4000
H u a n g \0
. . .
myName 0
6000
u n g \0
H e a d i n g t
o n \0 . . .
yourName 0
50Using typedef with arrays
- typedef int Boolean // names Boolean
as a data type - typedef char String20 21 // names
String20 as an array type - String20 myName // these declarations
- String20 yourName // allocate memory for
3 variables - Boolean isSeniorCitizen
5000
6000
7000
18
51Write a program that will...
- Read the ID numbers, hourly wages, and names, for
up to 50 persons from a data file. - Then display the ID number and hourly wage for
any person in the file whose name is entered at
the keyboard, or indicate that the person was not
located, if that is the case.
19
52Assume file has this form with data for no more
than 50 persons
4562 19.68 Dale Nell 1235 15.75
Weems Chip 6278 12.71 Headington
Mark . .
. .
. . .
. .
8754 17.96 Cooper Sonia 2460
14.97 Huang Jeff
20
53Parallel arrays hold related data
- const int MAX_PERSONS 50
- typedef char String20 21 // define data
type - .
- .
- .
- // declare 3 parallel arrays
- int idNums MAX_PERSONS
- float wages MAX_PERSONS
- String20 names MAX_PERSONS
- // holds up to 50 strings each with
- // up to 20 characters plus null character \0
21
54int idNums MAX_PERSONS
// parallel arraysfloat wages
MAX_PERSONS String20 names MAX_PERSONS
idNums 0 4562 wages 0 19.68
names 0 Dale Nell idNums 1
1235 wages 1 15.75
names 1 Weems Chip idNums 2
6278 wages 2 12.71 names
2 Headington Mark .
. . . . .
. . .
. . . .
. .
. . . idNums 48 8754 wages 48
17.96 names 48 Cooper Sonia
idNums 49 2460 wages 49 14.97
names 49 Huang Jeff
22
55Two-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 components position in
each dimension. -
56- 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 80
row 2, col 7 might be Arizonas high for August
57Finding the average high temperature for Arizona
- int total 0
- int month
- int average
- for ( month 0 month lt NUM_MONTHS month )
- total total stateHighs 2 month
-
- average int ( total / 12.0 0.5 )
58const int NUM_STATES 50 const int
NUM_MONTHS 12 int stateHighs NUM_STATES
NUM_MONTHS
rows columns
STORAGE
- In memory, C stores arrays in row order. The
first row is followed by the second row, etc.
Base Address
8000
8024
8048
. . .
12 highs for state 0 12 highs for state 1
etc. Alabama
Alaska first row
second row
59Implementation Level View
Base Address 8000
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.
60Two-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.
61 Use the two-dimensional stateHighs array to fill
a one-dimensional stateAverages array
- 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
Alaska Arizona
43 42 50 55 60 78 79 80 77 72 63 40 66 64 72 78
85 90 99 115 98 90 88 80
62void 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 lt NUM_STATES
state ) -
- total 0
- for ( month 0 month lt NUM_MONTHS
month ) - total stateHighs state month
- stateAverages state int ( total / 12.0
0.5 ) -
62
63 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 ) -
- .
- .
- .
63
64Declaring Multidimensional Arrays
- EXAMPLE OF THREE-DIMENSIONAL ARRAY
- const NUM_DEPTS 5 // mens,
womens, childrens, electronics, furniture - const NUM_MONTHS 12
- const NUM_STORES 3 // White Marsh,
Owings Mills, Towson - int monthlySales NUM_DEPTS NUM_MONTHS
NUM_STORES - rows columns sheets
- OR USING TYPEDEF
- typedef int MonthlySalesType NUM_DEPTS
NUM_MONTHS NUM_STORES - MonthlySalesType monthlySales
65- 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
monthlySales370 sales for
electronics in August at White Marsh
3 STORES sheets
5 DEPTS rows
65
12 MONTHS columns