C++ Programming: From Problem Analysis To Program Design, Fifth Edition
C++ Programming: From Problem Analysis To Program Design, Fifth Edition
C++ Programming: From Problem Analysis To Program Design, Fifth Edition
Objectives
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
C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2
Records (structs)
struct: collection of a fixed number of components (members), accessed by name
Members may be of different types
Syntax:
Assignment
Value of one struct variable can be assigned to another struct variable of the same type using an assignment statement The statement:
student = newStudent;
Assignment (cont'd.)
The assignment statement:
student = newStudent;
12
Input/Output
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
13
15
Arrays in structs
Two key items are associated with a list:
Values (elements) Length of the list
16
17
18
structs in Arrays
19
20
21
versus
22
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)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition 24
26
Use a struct to group the components Six people: array of size six Program requires total sales for each quarter
Use array of size four to store the data
C++ Programming: From Problem Analysis to Program Design, Fifth Edition 27
28
29
31
Summary
struct: collection of a fixed number of components Components can be of different types
Called members Accessed by name
Summary (cont'd.)
Dot (.) operator: member access operator
Used to access members of a struct
The only built-in operations on a struct are the assignment and member access Neither arithmetic nor relational operations are allowed on structs struct can be passed by value or reference A function can return a value of type struct structs can be members of other structs
C++ Programming: From Problem Analysis to Program Design, Fifth Edition 38