Title: C Programming: From Problem Analysis to Program Design, Second Edition
1C Programming From Problem Analysis to
Program Design, Second Edition
0
- Chapter 10 Records (structs)
2Objectives
0
- In this chapter you will
- Learn about records (structs)
- Examine various operations on a struct
- Explore ways to manipulate data using a struct
- Learn about the relationship between a struct and
functions - Discover how arrays are used in a struct
- Learn how to create an array of struct items
30
C Data Types
structured
simple
array struct union class
integral enum
char short int long bool
4C Data Types
0
- There are simple data types that hold only one
value - There are structured data types that hold
multiple values - The array was the first example of a structured
data type that can hold multiple values - The structure is the second example
5Structured Data Type
0
- A structured data type is a type in which each
value is a collection of component items. - the entire collection has a single name
- each component can be accessed individually
6C Structured Type
0
- often we have related information of various
types that wed like to store together for
convenient access under the same identifier, for
example . . .
7thisAnimal
0
5000
.id 2037581 .name
giant panda .genus
Ailuropoda .species melanoluka .count
ry China .age
18 .weight 234.6 .health
Good
8anotherAnimal
0
6000
.id 5281003 .name
llama .genus Lama .species
peruana .country Peru .age
7 .weight 278.5 .health
Excellent
9struct AnimalType
0
- struct AnimalType // declares a struct data
type - // does not allocate memory
- long id
- string name
- string genus
- string species
struct members - string country
- int age
- float weight
- string health
- // NOTE THE SEMICOLON
- AnimalType thisAnimal // declare variables
of AnimalType - AnimalType anotherAnimal
9
10struct type Declaration
0
- The struct declaration names a type and names the
members of the struct. - It does not allocate memory for any variables of
that type! - You still need to declare your struct variables.
11More about struct type declarations
0
- If the struct type declaration precedes all
functions it will be visible throughout the rest
of the file. If it is placed within a function,
only that function can use it. - It is common to place struct type declarations
with TypeNames in a (.h) header file and include
that file (more on this later). - It is possible for members of different struct
types to have the same identifiers. Also a
non-struct variable may have the same identifier
as a structure member.
12Accessing struct Members
0
- Dot ( period ) is the member selection operator.
- After the struct type declaration, the various
members can be used in your program only when
they are preceded by a struct variable name and a
dot. - EXAMPLES
- thisAnimal.weight
- anotherAnimal.country
13Valid operations on a struct member depend
only on its type
0
- thisAnimal.age 18
- thisAnimal.id 2037581
- cin gtgt thisAnimal.weight
- getline ( cin, thisAnimal.species )
- thisAnimal.name giant panda
- thisAnimal.genus 0 toupper
(thisAnimal.genus 0 ) - thisAnimal.age
14Aggregate Operation
0
- is an operation on a data structure as a whole,
as opposed to an operation on an individual
component of the data structure
15Aggregate struct Operations
0
- I/O, arithmetic, and comparisons of entire struct
variables are NOT ALLOWED! - Operations valid on an entire struct type
variable - assignment to another struct variable of same
type, -
- pass to a function as argument (by value or by
reference), - return as value of a function
16Examples of aggregate struct operations
0
- anotherAnimal thisAnimal // assignment
- WriteOut(thisAnimal) // value parameter
- ChangeWeightAndAge(thisAnimal) // reference
parameter - thisAnimal GetAnimalData( ) // return value
of function - NOW WELL WRITE FUNCTIONS USED HERE . . .
170
- void WriteOut( / in / AnimalType
thisAnimal) - // Prints out values of all members of thisAnimal
- // Precondition all members of thisAnimal
are assigned - // Postcondition all members have been
written out -
- cout ltlt ID ltlt thisAnimal.id ltlt
thisAnimal.name ltlt endl - cout ltlt thisAnimal.genus ltlt
thisAnimal.species ltlt endl - cout ltlt thisAnimal.country ltlt endl
- cout ltlt thisAnimal.age ltlt years ltlt
endl - cout ltlt thisAnimal.weight ltlt lbs. ltlt
endl - cout ltlt General health
17
18Passing a struct Type by Reference
0
- void ChangeAge ( / inout / AnimalType
thisAnimal ) - // Adds 1 to age
- // Precondition thisAnimal.age is assigned
- // Postcondition thisAnimal.age
thisAnimal.age_at_entry 1 -
-
- thisAnimal.age
-
190
- AnimalType GetAnimalData ( void )
- // Obtains all information about an animal from
keyboard - // Postcondition
- // Function value AnimalType members entered
at kbd -
- AnimalType thisAnimal
- char response
- do // have user enter all members until
they are correct - .
- .
- .
- while (response ! Y )
- return thisAnimal
-
19
20Hierarchical Structures
0
- The type of a struct member can be another struct
type. This is called nested or hierarchical
structures. - Hierarchical structures are very useful when
there is much detailed information in each
record. - FOR EXAMPLE . . .
21struct MachineRec
0
- Information about each machine in a shop
contains - an idNumber,
- a written description,
- the purchase date,
- the cost,
- and a history (including failure rate, number
of days down, and date of last service).
22- struct DateType
- int month // Assume 1 . . 12
- int day // Assume 1 . . 31
- int year // Assume 1900 . . 2050
-
- struct StatisticsType
- float failRate
- DateType lastServiced // DateType is
a struct type - int downDays
-
- struct MachineRec
- int idNumber
- string description
- StatisticsType history //
StatisticsType is a struct type - DateType purchaseDate
- float cost
-
0
22
23struct type variable machine
0
7000
5719 DRILLING
3 21 1995 8000.0
.02 1 25 1999 4
.month .day .year
.month .day .year
.failrate .lastServiced .downdays
.idNumber .description . history
.purchaseDate .cost
machine.history.lastServiced.year has value 1999
24Another Struct Example
0
- An example of a studentData struct
- struct studentData
-
- string firstName
- string lastName
- char courseGrade
- float testScore
- float programmingScore
- float GPA
- // NOTE THE SEMICOLON
25Declaring a struct
0
- After you have defined a struct, you can declare
variables in your program to be a that struct - studentData student
- studentData newStudent
260
27Assignment
0
- You can copy one structure to another if they are
the same type of - student newStudent
- You can copy individual members
- newStudent.lastName student.lastName
- Or into a variable of the correct type
- thisStudentName student.lastName
28Comparison (Relational Operators)
0
- Compare struct variables member-wise (NOT THE
WHOLE STRUCTURE) - To compare the values of student and newStudent
- if(student.firstName newStudent.firstName
- student.lastName newStudent.lastName)
- .
- .
- .
29Input/Output
0
- No aggregate input/output operations on a struct
variable - Data in a struct variable must be read one member
at a time - The contents of a struct variable must be written
one member at a time
30struct Variables and Functions
0
- A struct variable can be passed as a parameter by
value or by reference - A function can return a value of type struct
310
32Arrays in structs
0
- Two key items are associated with a list
- Values (elements)
- Length of the list
- Define a struct containing both items
- const arraySize 1000
- struct listType
-
- int listElemarraySize //array containing
the list - int listLength //length of the
list -
330
340
35Programming Example
0
- A company has six salespeople
- Every month they go on road trips to sell the
companys product - At the end of each month, the total sales for
each salesperson, salespersons ID, and the
month, are recorded in a file - At the end of each year, the manager of the
company asks for a report
36Output Format
0
- ----------- Annual Sales Report -------------
- ID QT1 QT2 QT3 QT4
Total - __________________________________________________
_____________ - 12345 1892.00 0.00 494.00 322.00
2708.00 - 32214 343.00 892.00 9023.00 0.00
10258.00 - 23422 1395.00 1901.00 0.00 0.00
3296.00 - 57373 893.00 892.00 8834.00 0.00
10619.00 - 35864 2882.00 1221.00 0.00 1223.00
5326.00 - 54654 893.00 0.00 392.00 3420.00
4705.00 - Total 8298.00 4906.00 18743.00 4965.00
- Max Sale by SalesPerson ID 57373, Amount
10619.00 - Max Sale by Quarter Quarter 3, Amount
18743.00 - QT1 stands for quarter 1 (months 1 to 3),
QT2 for quarter 2 (months 4 to 6), QT3 for
quarter 3 (months 7 to 9) and QT4 for quarter 4
(months 10 to 12)
37Programming Example
0
- The salespeople IDs are stored in one file sales
data are stored in another file - The sales data is in the following form
- salesPersonID month saleAmount
- .
- .
- .
- Sales data are not ordered
38Input/Output
0
- Input file containing each salespersons ID, and
a second file containing the sales data - Output file containing annual sales report in
the above format
39Problem Analysis
0
- Main components for each sales person
- ID
- Quarterly sales amount
- Total annual sales amount
- Because the components are of different types,
group them in a struct
40Program Analysis (continued)
0
- There are six people, so an array of 6 components
is used - Because the program requires the companys total
sales for each quarter - We need an array of four components to store the
data
410
42Program Analysis (continued)
0
- Read the salespeople IDs into the array
salesPersonList - Initialize the quarterly sales and total sales
for each salesperson to 0
43Program Analysis (continued)
0
- For each entry in the file containing the sales
data - Read ID, month, sale amount for the month
- Search salesPersonList to locate the component
corresponding to this salesperson - Determine the quarter corresponding to the month
- Update the sales for the quarter by adding the
sale amount for the month
44Program Analysis (continued)
0
- Once the sales data file is processed
- Calculate the total sale by salesman
- Calculate the total sale by quarter
- Print the report
45Algorithm Design
0
- Translates into the following algorithm
- Initialize the array sales
- Process the sales data
- Calculate the total sale by salesman
- Calculate the total sale by quarter
- Print the report
- Calculate and print maximum sale by salesman
- Calculate and print maximum sale by quarter
46Main Algorithm
0
- Declare the variables
- Prompt user to enter name of file containing the
salespersons ID data - Read the name of the input file
- Open the input file
- If input file does not exist, exit
- Initialize the array salesPersonList by calling
the function initialize
47Main Algorithm (continued)
0
- Close input file containing salespersons ID
- Prompt user to enter name of file containing
sales data - Read the name of the input file
- Open the input file
- If input file does not exist, exit
- Prompt user to enter name of output file
- Read the name of the output file
48Main Algorithm (continued)
0
- Open the output file
- Output data to two decimal places
- Process sales data
- Call the function getData
49Main Algorithm (continued)
0
- Calculate the total sale by quarter by calling
the function saleByQuarter - Calculate the total sale by salesman by calling
the function totalSaleByPerson - Print the report in the tabular form. Call the
function printReport - Find and print the salesperson who produces the
maximum sales for the year by calling the
function maxSaleByPerson
50Main Algorithm (continued)
0
- Find and print the quarter producing the maximum
sale for the year by calling the function
maxSaleByQuarter - Close files
51Organization of Large Programs
0
- Large programs are composed of multiple source
files. Each source file is compiled by dev-C
then linked into an executable program - So that struct definitions can be used in all the
source files, they are put in header (include
files) - The header file is then included in the source
file
52Include Files
0
- The include statement inserts the named file in
this source code file - It is typically used for definitions needed by
the source file - Structures are the first example of the need for
you to use your own include file - Using include files means that you only define
the structure once no matter how many files it is
used in
53Include File Example
0
- // Functions for the sales by quarter program
- include ltiostreamgt // system runtime files
- include ltfstreamgt
- include ltiomanipgt
- include ltstringgt
- using namespace std
- include "salesPerson.h" // sales person header
file
54System Includes vs. User Includes
0
- Note how system files are included
- include ltiostreamgt // using angle brackets
- Note how your header files are included
- using namespace std
- include "salesPerson.h"
- Put inside double quotes after the using statement
55Summary
0
- Struct collection of a fixed number of
components - Components can be of different types
- struct is a reserved word
- No memory is allocated for a struct memory is
allocated for struct variables when declared - Components of a struct are called members
56Summary
0
- struct components are accessed by name
- Dot (.) operator is called the member access
operator - Members of a struct are accessed using the dot
(.) operator - The only built-in operations on a struct are the
assignment and member access
57Summary
0
- Neither arithmetic nor relational operations are
allowed on the entire structure - structures can be passed by value or reference
- A function can return a structure
- A structure can be a member of another structure