CHAPTER-7
CHAPTER-7
STRUCTURES
STRUCTURES
STRUCTURES
STRUCTURES
 C++ allows you to
C++ allows you to group a set of variables
group a set of variables together into a
together into a single item
single item known as a
known as a
structure
structure.
.
 A
A structure
structure is a set of
is a set of diverse types of data
diverse types of data grouped together under a unique
grouped together under a unique
declaration.
declaration.
 C++ gives you the ability to create a
C++ gives you the ability to create a relationship between variables
relationship between variables by
by packaging
packaging
them together
them together into a
into a structure
structure
 A
A structure
structure bundles together
bundles together items that logically belong together
items that logically belong together.
.
 The
The members of a structure
members of a structure are
are attributes
attributes describing same
describing same object
object.
.
 For example, a
For example, a payroll system
payroll system might keep the variables shown in the following table.
might keep the variables shown in the following table.
 All of the variables
All of the variables listed in this
listed in this
table
table are related
are related because
because they can
they can
hold data about the same employee
hold data about the same employee.
.
STRUCTURES
STRUCTURES
 Before a structure can be used, it must be declared. Here is the general format
Before a structure can be used, it must be declared. Here is the general format
of a structure declaration:
of a structure declaration:
struct tag
struct tag //
// Structure declaration begins with the key word struct and a name.
Structure declaration begins with the key word struct and a name.
{
{
// Variable declarations go here.
// Variable declarations go here.
};
}; // Notice the required semi-colon.
// Notice the required semi-colon.
 The
The tag
tag is the
is the name of the structure
name of the structure. It is
. It is used like a data type name
used like a data type name.
.
 The
The variable declarations
variable declarations that appear inside the braces
that appear inside the braces declare the
declare the
members
members of the structure
of the structure.
.
 Here is an example of a structure declaration that holds the payroll data listed in table above:
Here is an example of a structure declaration that holds the payroll data listed in table above:
struct PayRoll
struct PayRoll
{
{
int empNumber;
int empNumber;
char name[30];
char name[30];
double hours,
double hours,
payRate,
payRate,
grossPay;
grossPay;
};
};
STRUCTURES
STRUCTURES
 The
The structure declaration
structure declaration in our example creates a
in our example creates a new data type
new data type named
named
PayRoll
PayRoll.
.
 Once the data type has been created you can
Once the data type has been created you can define variables of this type
define variables of this type
with simple definition statements.
with simple definition statements.
 For example, the following statement defines a variable called
For example, the following statement defines a variable called deptHead
deptHead:
:
PayRoll deptHead;
PayRoll deptHead;
 The
The data type
data type of
of deptHead
deptHead is a
is a PayRoll
PayRoll structure.
structure.
 The
The structure tag
structure tag,
, PayRoll
PayRoll, is placed
, is placed before the variable name
before the variable name just as the
just as the
word
word int
int or
or double
double would be to define variables of those types.
would be to define variables of those types.
STRUCTURES
STRUCTURES
 Structure variables
Structure variables contain
contain other variables
other variables known as
known as members
members.
.
 Because
Because deptHead
deptHead is a
is a PayRoll
PayRoll structure, it contains the
structure, it contains the five members
five members listed
listed
in the
in the Pay-Roll structure
Pay-Roll structure declaration.
declaration.
 This is illustrated in the following figure.
This is illustrated in the following figure.
STRUCTURES
STRUCTURES
 Just as it’s possible to define
Just as it’s possible to define multiple int
multiple int or
or double
double variables
variables, it’s possible to
, it’s possible to
define
define multiple structure variables
multiple structure variables in a
in a program
program.
.
 The following statement defines
The following statement defines three PayRoll variables
three PayRoll variables: deptHead, foreman,
: deptHead, foreman,
and associate.
and associate.
PayRoll deptHead, foreman, associate;
PayRoll deptHead, foreman, associate;
 The following figure illustrates the existence of these three variables.
The following figure illustrates the existence of these three variables.
STRUCTURES
STRUCTURES
 Each of these variables is a
Each of these variables is a separate
separate instance
instance of the
of the PayRoll structure
PayRoll structure with its
with its
own memory allocated to hold its members.
own memory allocated to hold its members.
 Each structure variable
Each structure variable contains
contains members with the same name
members with the same name.
.
 Here are some
Here are some other examples of structure declarations
other examples of structure declarations and
and variable definitions
variable definitions:
:
// Structure declaration
// Structure declaration
struct Time
struct Time
{
{
int hours, minutes,
int hours, minutes,
seconds;
seconds;
};
};
// Definition of a Time structure variable.
// Definition of a Time structure variable.
Time now;
Time now;
// Structure declaration
// Structure declaration
struct Date
struct Date
{
{
int day, month, year;
int day, month, year;
};
};
// Definition of two Date structure
// Definition of two Date structure
variables
variables
Date today, yesterday;
Date today, yesterday;
Accessing Structure Members
Accessing Structure Members
 C++ provides the
C++ provides the dot operator
dot operator (a
(a period
period) to
) to access the individual members
access the individual members of a structure.
of a structure.
 Using our example of
Using our example of deptHead
deptHead as a
as a PayRoll structure variable
PayRoll structure variable, the following statement
, the following statement
demonstrates how to access the
demonstrates how to access the empNumber
empNumber member
member:
:
deptHead.empNumber = 475;
deptHead.empNumber = 475;
 In this statement, the number
In this statement, the number 475
475 is assigned to the
is assigned to the empNumber
empNumber
 The
The dot operator
dot operator connects the
connects the name of the member
name of the member with the
with the name of the structure
name of the structure
variable
variable it belongs to.
it belongs to.
 For example, the following statements display the
For example, the following statements display the contents of deptHead’s members
contents of deptHead’s members:
:
cout << deptHead.empNumber << endl;
cout << deptHead.empNumber << endl;
cout << deptHead.name << endl;
cout << deptHead.name << endl;
cout << deptHead.hours << endl;
cout << deptHead.hours << endl;
cout << deptHead.payRate << endl;
cout << deptHead.payRate << endl;
cout << deptHead.grossPay << endl;
cout << deptHead.grossPay << endl;
Displaying and Comparing Structure Variables
Displaying and Comparing Structure Variables
 In
In each member
each member of the
of the employee structure variable
employee structure variable is displayed separately.
is displayed separately.
 Entire contents
Entire contents of a
of a structure variable
structure variable cannot be
cannot be displayed
displayed by simply passing
by simply passing
the
the whole variable
whole variable to
to cout
cout.
.
 For example, the following statement will not work.
For example, the following statement will not work.
cout << employee << endl; // Error!
cout << employee << endl; // Error!
 You
You cannot
cannot perform
perform comparison operations
comparison operations on
on entire structure variables
entire structure variables.
.
 For example, if
For example, if employee1
employee1 and
and employee2
employee2 are both
are both Payroll structure
Payroll structure
variables
variables, this comparison will cause an error.
, this comparison will cause an error.
if (employee1 == employee2) // Error!
if (employee1 == employee2) // Error!
 The following comparison is perfectly legal.
The following comparison is perfectly legal.
if (employee1.hours == employee2.hours) // Legal
if (employee1.hours == employee2.hours) // Legal
 The following program segment illustrates how they can be passed as arguments to functions and can
The following program segment illustrates how they can be passed as arguments to functions and can
be compared.
be compared.
struct Circle
struct Circle // Declare what a Circle structure looks like
// Declare what a Circle structure looks like
{
{
double radius;
double radius;
double diameter;
double diameter;
double area;
double area;
};
};
const double PI = 3.14159;
const double PI = 3.14159;
main() {
main() {
Circle c1, c2;
Circle c1, c2; // Define 2 Circle structure variables
// Define 2 Circle structure variables
cout << "Enter the diameter of circle 1 and circle 2: : ";
cout << "Enter the diameter of circle 1 and circle 2: : ";
cin >> c1.diameter >> c2.diameter;
cin >> c1.diameter >> c2.diameter;
c1.radius = c1.diameter / 2;
c1.radius = c1.diameter / 2;
c1.area = PI * pow(c1.radius, 2.0);
c1.area = PI * pow(c1.radius, 2.0);
c2.radius = c2.diameter / 2;
c2.radius = c2.diameter / 2;
c2.area = PI * pow(c2.radius, 2.0);
c2.area = PI * pow(c2.radius, 2.0);
cout << "nThe radius and area of the circles aren";
cout << "nThe radius and area of the circles aren";
cout << "Circle 1 -- Radius: " << c1.radius<< " Area: " << c1.area << endl;
cout << "Circle 1 -- Radius: " << c1.radius<< " Area: " << c1.area << endl;
cout << "Circle 2 -- Radius: " << c2.radius<< " Area: " << c2.area << endl;
cout << "Circle 2 -- Radius: " << c2.radius<< " Area: " << c2.area << endl;
if (c1.area == c2.area)
if (c1.area == c2.area)
cout << "The two circles have the same area.nn";
cout << "The two circles have the same area.nn";
}
}
Initializing a Structure
Initializing a Structure
 The
The members
members of a
of a structure variable
structure variable can be initialized with an
can be initialized with an initialization list
initialization list.
.
 The
The items
items in the list are
in the list are separated by
separated by commas
commas and
and surrounded by braces
surrounded by braces.
.
 Suppose, for example, the following
Suppose, for example, the following Date
Date structure has been declared:
structure has been declared:
struct Date
struct Date
{
{
int day, month, year;
int day, month, year;
};
};
 A
A Date
Date variable
variable can now be
can now be defined
defined and
and initialized
initialized by following the
by following the variable name
variable name
with the
with the assignment operator
assignment operator and an
and an initialization list
initialization list, as shown here:
, as shown here:
Date birthday = {23, 8, 1983};
Date birthday = {23, 8, 1983};
Initializing a Structure
Initializing a Structure
Date birthday = {23, 8, 1983};
Date birthday = {23, 8, 1983};
 This statement defines
This statement defines birthday to be a variable
birthday to be a variable which is
which is a Date structure.
a Date structure.
 The
The values
values following the
following the definition
definition are
are assigned to its members in order
assigned to its members in order.
.
 So
So birthday
birthday has been initialized as follows:
has been initialized as follows:
 If we know the birthday to be stored is
If we know the birthday to be stored is August 23
August 23, but do
, but do not know
not know the
the
year
year, the variable could be defined and initialized like this:
, the variable could be defined and initialized like this:
Date birthday = {23, 8);
Date birthday = {23, 8);
Initializing a Structure
Initializing a Structure
 C++
C++ does
does not provide
not provide a way to
a way to skip members
skip members when using an
when using an initialization list
initialization list.
.
 If you leave a
If you leave a structure member uninitialized
structure member uninitialized, however, you must
, however, you must leave all the
leave all the
members
members that follow it
that follow it uninitialized as well
uninitialized as well.
.
 The following statement, which attempts to skip the initialization of the month
The following statement, which attempts to skip the initialization of the month
member, is
member, is not
not legal
legal.
.
Date birthday = {23, , 1983); // Illegal!
Date birthday = {23, , 1983); // Illegal!
 You
You cannot initialize a structure member
cannot initialize a structure member in the
in the declaration
declaration of
of the structure.
the structure.
 For example, the following declaration is illegal:
For example, the following declaration is illegal:
// Illegal structure declaration
// Illegal structure declaration
struct Date {
struct Date {
int day = 23,
int day = 23,
month = 8,
month = 8,
year = 1983;
year = 1983;
};
};
Nested Structures
Nested Structures
 It is possible for a
It is possible for a structure variable
structure variable to be a
to be a member of another structure
member of another structure
variable
variable.
.
 When
When some of the attributes
some of the attributes are
are related
related and
and form
form a
a logical subgroup
logical subgroup of the
of the
object’s attributes, it is
object’s attributes, it is possible to bundle
possible to bundle them together
them together and use a
and use a nested
nested
structure
structure.
.
 For example, consider the following structure declarations:
For example, consider the following structure declarations:
struct Costs
struct Costs
{
{
double wholesale;
double wholesale;
double retail;
double retail;
};
};
struct Item
struct Item
{
{
char partNum[30];
char partNum[30];
char description[30];
char description[30];
Costs pricing;
Costs pricing;
};
};
 The
The Costs structure
Costs structure has
has two double
two double members,
members, wholesale
wholesale and
and retail
retail.
.
 The
The Item structure
Item structure has
has three
three members.
members.
 The first two,
The first two, partNum
partNum and
and description
description, are character objects.
, are character objects.
 The third,
The third, pricing
pricing, is a
, is a nested Costs structure
nested Costs structure.
.
Nested Structures
Nested Structures
 Assume variable
Assume variable widget
widget is defined to be an
is defined to be an Item structure
Item structure:
:
Item widget;
Item widget;
 The following figure illustrates its members.
The following figure illustrates its members.
 They would be accessed as follows:
They would be accessed as follows:
widget.partnum = "123A";
widget.partnum = "123A";
widget.description = "iron widget";
widget.description = "iron widget";
widget.pricing.wholesale = 100.0;
widget.pricing.wholesale = 100.0;
widget.pricing.retail = 150.0;
widget.pricing.retail = 150.0;
Arrays of Structures
Arrays of Structures
 Because
Because structures
structures can
can hold several items of varying data types
hold several items of varying data types, a
, a single
single
array of structures
array of structures can be used
can be used in place of several arrays of regular variables
in place of several arrays of regular variables.
.
 An
An array of structures
array of structures is defined like any other array.
is defined like any other array.
 Assume the following structure declaration exists in a program:
Assume the following structure declaration exists in a program:
struct BookInfo {
struct BookInfo {
char title[100];
char title[100];
char author[50];
char author[50];
char publisher[100];
char publisher[100];
double price;
double price;
};
};
 The following statement
The following statement defines an array
defines an array,
, bookList
bookList, which has
, which has 20 elements
20 elements.
.
 Each
Each element
element is a
is a BookInfo structure
BookInfo structure.
.
BookInfo bookList[20];
BookInfo bookList[20];
 Each element
Each element of the
of the array
array may be accessed through a
may be accessed through a subscript
subscript.
.
 For example,
For example, bookList[0]
bookList[0] is the
is the first structure in the array
first structure in the array,
, bookList[1]
bookList[1] is the
is the second
second,
,
and so forth.
and so forth.
 To
To access a member of any element
access a member of any element, simply
, simply place the dot operator
place the dot operator and
and member name
member name after
after
the
the subscript
subscript.
.
 For example, the following expression refers to the
For example, the following expression refers to the title
title member of
member of
bookList[5]
bookList[5]:
:
bookList[5].title
bookList[5].title
 The following
The following loop
loop steps through the array
steps through the array, displaying the information stored in each
, displaying the information stored in each
element:
element:
for (int index = 0; index < 20; index++) {
for (int index = 0; index < 20; index++) {
cout << bookList[index].title << endl;
cout << bookList[index].title << endl;
cout << bookList[index].author << endl;
cout << bookList[index].author << endl;
cout << bookList[index].publisher << endl;
cout << bookList[index].publisher << endl;
cout << bookList[index].price << endl << endl;
cout << bookList[index].price << endl << endl;
}
}
struct BookInfo {
struct BookInfo {
char title[100];
char title[100];
char author[50];
char author[50];
char publisher[100];
char publisher[100];
double price;
double price;
};
};
 Note:
Note: Because the members
Because the members title
title,
, author
author, and
, and publisher
publisher are
are character objects
character objects, their
, their
individual elements
individual elements can be accessed as well.
can be accessed as well.
 The following statement displays the
The following statement displays the first character
first character of the
of the title
title member of
member of
bookList[10]
bookList[10]:
:
cout << bookList[10].title[0];
cout << bookList[10].title[0];
 And the following statement stores the character
And the following statement stores the character ‘t’
‘t’ in the
in the fourth
fourth
position
position of the
of the publisher
publisher member of
member of bookList[2]
bookList[2]:
:
bookList[2].publisher[3] = 't';
bookList[2].publisher[3] = 't';
 // This program uses an array of structures to hold employee payroll data.
struct PayInfo
{
int hours; // Hours worked
double payRate; // Hourly pay rate
};
int main ()
{
const int NUM_EMPS = 5;
int index;
PayInfo workers[NUM_EMPS]; // Define an array of structures
double grossPay;
cout << "Enter the hours worked and hourly pay rates of " << NUM_EMPS << " employees. n";
for (index = 0; index < NUM_EMPS; index++)
{
cout << "Hours worked by employee #" << (index + 1) << ": ";
cin >> workers[index].hours;
cout << "Hourly pay rate for employee #" << (index + 1) << ": ";
cin >> workers[index].payRate;
}
cout << "nHere is the gross pay for each employee:n";
for (index = 0; index < NUM_EMPS; index++)
{
grossPay = workers[index].hours * workers[index].payRate;
cout << "Employee #" << (index + 1) << ": $" << setw(7) << grossPay << endl;
}
}
End of CH-7
End of CH-7

CHAPTERGAHAhsghdfsfdsfsdfsfdsfsdfAGSHagsh-7.ppt

  • 1.
  • 2.
    STRUCTURES STRUCTURES  C++ allowsyou to C++ allows you to group a set of variables group a set of variables together into a together into a single item single item known as a known as a structure structure. .  A A structure structure is a set of is a set of diverse types of data diverse types of data grouped together under a unique grouped together under a unique declaration. declaration.  C++ gives you the ability to create a C++ gives you the ability to create a relationship between variables relationship between variables by by packaging packaging them together them together into a into a structure structure  A A structure structure bundles together bundles together items that logically belong together items that logically belong together. .  The The members of a structure members of a structure are are attributes attributes describing same describing same object object. .  For example, a For example, a payroll system payroll system might keep the variables shown in the following table. might keep the variables shown in the following table.  All of the variables All of the variables listed in this listed in this table table are related are related because because they can they can hold data about the same employee hold data about the same employee. .
  • 3.
    STRUCTURES STRUCTURES  Before astructure can be used, it must be declared. Here is the general format Before a structure can be used, it must be declared. Here is the general format of a structure declaration: of a structure declaration: struct tag struct tag // // Structure declaration begins with the key word struct and a name. Structure declaration begins with the key word struct and a name. { { // Variable declarations go here. // Variable declarations go here. }; }; // Notice the required semi-colon. // Notice the required semi-colon.  The The tag tag is the is the name of the structure name of the structure. It is . It is used like a data type name used like a data type name. .  The The variable declarations variable declarations that appear inside the braces that appear inside the braces declare the declare the members members of the structure of the structure. .  Here is an example of a structure declaration that holds the payroll data listed in table above: Here is an example of a structure declaration that holds the payroll data listed in table above: struct PayRoll struct PayRoll { { int empNumber; int empNumber; char name[30]; char name[30]; double hours, double hours, payRate, payRate, grossPay; grossPay; }; };
  • 4.
    STRUCTURES STRUCTURES  The The structuredeclaration structure declaration in our example creates a in our example creates a new data type new data type named named PayRoll PayRoll. .  Once the data type has been created you can Once the data type has been created you can define variables of this type define variables of this type with simple definition statements. with simple definition statements.  For example, the following statement defines a variable called For example, the following statement defines a variable called deptHead deptHead: : PayRoll deptHead; PayRoll deptHead;  The The data type data type of of deptHead deptHead is a is a PayRoll PayRoll structure. structure.  The The structure tag structure tag, , PayRoll PayRoll, is placed , is placed before the variable name before the variable name just as the just as the word word int int or or double double would be to define variables of those types. would be to define variables of those types.
  • 5.
    STRUCTURES STRUCTURES  Structure variables Structurevariables contain contain other variables other variables known as known as members members. .  Because Because deptHead deptHead is a is a PayRoll PayRoll structure, it contains the structure, it contains the five members five members listed listed in the in the Pay-Roll structure Pay-Roll structure declaration. declaration.  This is illustrated in the following figure. This is illustrated in the following figure.
  • 6.
    STRUCTURES STRUCTURES  Just asit’s possible to define Just as it’s possible to define multiple int multiple int or or double double variables variables, it’s possible to , it’s possible to define define multiple structure variables multiple structure variables in a in a program program. .  The following statement defines The following statement defines three PayRoll variables three PayRoll variables: deptHead, foreman, : deptHead, foreman, and associate. and associate. PayRoll deptHead, foreman, associate; PayRoll deptHead, foreman, associate;  The following figure illustrates the existence of these three variables. The following figure illustrates the existence of these three variables.
  • 7.
    STRUCTURES STRUCTURES  Each ofthese variables is a Each of these variables is a separate separate instance instance of the of the PayRoll structure PayRoll structure with its with its own memory allocated to hold its members. own memory allocated to hold its members.  Each structure variable Each structure variable contains contains members with the same name members with the same name. .  Here are some Here are some other examples of structure declarations other examples of structure declarations and and variable definitions variable definitions: : // Structure declaration // Structure declaration struct Time struct Time { { int hours, minutes, int hours, minutes, seconds; seconds; }; }; // Definition of a Time structure variable. // Definition of a Time structure variable. Time now; Time now; // Structure declaration // Structure declaration struct Date struct Date { { int day, month, year; int day, month, year; }; }; // Definition of two Date structure // Definition of two Date structure variables variables Date today, yesterday; Date today, yesterday;
  • 8.
    Accessing Structure Members AccessingStructure Members  C++ provides the C++ provides the dot operator dot operator (a (a period period) to ) to access the individual members access the individual members of a structure. of a structure.  Using our example of Using our example of deptHead deptHead as a as a PayRoll structure variable PayRoll structure variable, the following statement , the following statement demonstrates how to access the demonstrates how to access the empNumber empNumber member member: : deptHead.empNumber = 475; deptHead.empNumber = 475;  In this statement, the number In this statement, the number 475 475 is assigned to the is assigned to the empNumber empNumber  The The dot operator dot operator connects the connects the name of the member name of the member with the with the name of the structure name of the structure variable variable it belongs to. it belongs to.  For example, the following statements display the For example, the following statements display the contents of deptHead’s members contents of deptHead’s members: : cout << deptHead.empNumber << endl; cout << deptHead.empNumber << endl; cout << deptHead.name << endl; cout << deptHead.name << endl; cout << deptHead.hours << endl; cout << deptHead.hours << endl; cout << deptHead.payRate << endl; cout << deptHead.payRate << endl; cout << deptHead.grossPay << endl; cout << deptHead.grossPay << endl;
  • 9.
    Displaying and ComparingStructure Variables Displaying and Comparing Structure Variables  In In each member each member of the of the employee structure variable employee structure variable is displayed separately. is displayed separately.  Entire contents Entire contents of a of a structure variable structure variable cannot be cannot be displayed displayed by simply passing by simply passing the the whole variable whole variable to to cout cout. .  For example, the following statement will not work. For example, the following statement will not work. cout << employee << endl; // Error! cout << employee << endl; // Error!  You You cannot cannot perform perform comparison operations comparison operations on on entire structure variables entire structure variables. .  For example, if For example, if employee1 employee1 and and employee2 employee2 are both are both Payroll structure Payroll structure variables variables, this comparison will cause an error. , this comparison will cause an error. if (employee1 == employee2) // Error! if (employee1 == employee2) // Error!  The following comparison is perfectly legal. The following comparison is perfectly legal. if (employee1.hours == employee2.hours) // Legal if (employee1.hours == employee2.hours) // Legal
  • 10.
     The followingprogram segment illustrates how they can be passed as arguments to functions and can The following program segment illustrates how they can be passed as arguments to functions and can be compared. be compared. struct Circle struct Circle // Declare what a Circle structure looks like // Declare what a Circle structure looks like { { double radius; double radius; double diameter; double diameter; double area; double area; }; }; const double PI = 3.14159; const double PI = 3.14159; main() { main() { Circle c1, c2; Circle c1, c2; // Define 2 Circle structure variables // Define 2 Circle structure variables cout << "Enter the diameter of circle 1 and circle 2: : "; cout << "Enter the diameter of circle 1 and circle 2: : "; cin >> c1.diameter >> c2.diameter; cin >> c1.diameter >> c2.diameter; c1.radius = c1.diameter / 2; c1.radius = c1.diameter / 2; c1.area = PI * pow(c1.radius, 2.0); c1.area = PI * pow(c1.radius, 2.0); c2.radius = c2.diameter / 2; c2.radius = c2.diameter / 2; c2.area = PI * pow(c2.radius, 2.0); c2.area = PI * pow(c2.radius, 2.0); cout << "nThe radius and area of the circles aren"; cout << "nThe radius and area of the circles aren"; cout << "Circle 1 -- Radius: " << c1.radius<< " Area: " << c1.area << endl; cout << "Circle 1 -- Radius: " << c1.radius<< " Area: " << c1.area << endl; cout << "Circle 2 -- Radius: " << c2.radius<< " Area: " << c2.area << endl; cout << "Circle 2 -- Radius: " << c2.radius<< " Area: " << c2.area << endl; if (c1.area == c2.area) if (c1.area == c2.area) cout << "The two circles have the same area.nn"; cout << "The two circles have the same area.nn"; } }
  • 11.
    Initializing a Structure Initializinga Structure  The The members members of a of a structure variable structure variable can be initialized with an can be initialized with an initialization list initialization list. .  The The items items in the list are in the list are separated by separated by commas commas and and surrounded by braces surrounded by braces. .  Suppose, for example, the following Suppose, for example, the following Date Date structure has been declared: structure has been declared: struct Date struct Date { { int day, month, year; int day, month, year; }; };  A A Date Date variable variable can now be can now be defined defined and and initialized initialized by following the by following the variable name variable name with the with the assignment operator assignment operator and an and an initialization list initialization list, as shown here: , as shown here: Date birthday = {23, 8, 1983}; Date birthday = {23, 8, 1983};
  • 12.
    Initializing a Structure Initializinga Structure Date birthday = {23, 8, 1983}; Date birthday = {23, 8, 1983};  This statement defines This statement defines birthday to be a variable birthday to be a variable which is which is a Date structure. a Date structure.  The The values values following the following the definition definition are are assigned to its members in order assigned to its members in order. .  So So birthday birthday has been initialized as follows: has been initialized as follows:  If we know the birthday to be stored is If we know the birthday to be stored is August 23 August 23, but do , but do not know not know the the year year, the variable could be defined and initialized like this: , the variable could be defined and initialized like this: Date birthday = {23, 8); Date birthday = {23, 8);
  • 13.
    Initializing a Structure Initializinga Structure  C++ C++ does does not provide not provide a way to a way to skip members skip members when using an when using an initialization list initialization list. .  If you leave a If you leave a structure member uninitialized structure member uninitialized, however, you must , however, you must leave all the leave all the members members that follow it that follow it uninitialized as well uninitialized as well. .  The following statement, which attempts to skip the initialization of the month The following statement, which attempts to skip the initialization of the month member, is member, is not not legal legal. . Date birthday = {23, , 1983); // Illegal! Date birthday = {23, , 1983); // Illegal!  You You cannot initialize a structure member cannot initialize a structure member in the in the declaration declaration of of the structure. the structure.  For example, the following declaration is illegal: For example, the following declaration is illegal: // Illegal structure declaration // Illegal structure declaration struct Date { struct Date { int day = 23, int day = 23, month = 8, month = 8, year = 1983; year = 1983; }; };
  • 14.
    Nested Structures Nested Structures It is possible for a It is possible for a structure variable structure variable to be a to be a member of another structure member of another structure variable variable. .  When When some of the attributes some of the attributes are are related related and and form form a a logical subgroup logical subgroup of the of the object’s attributes, it is object’s attributes, it is possible to bundle possible to bundle them together them together and use a and use a nested nested structure structure. .  For example, consider the following structure declarations: For example, consider the following structure declarations: struct Costs struct Costs { { double wholesale; double wholesale; double retail; double retail; }; }; struct Item struct Item { { char partNum[30]; char partNum[30]; char description[30]; char description[30]; Costs pricing; Costs pricing; }; };  The The Costs structure Costs structure has has two double two double members, members, wholesale wholesale and and retail retail. .  The The Item structure Item structure has has three three members. members.  The first two, The first two, partNum partNum and and description description, are character objects. , are character objects.  The third, The third, pricing pricing, is a , is a nested Costs structure nested Costs structure. .
  • 15.
    Nested Structures Nested Structures Assume variable Assume variable widget widget is defined to be an is defined to be an Item structure Item structure: : Item widget; Item widget;  The following figure illustrates its members. The following figure illustrates its members.  They would be accessed as follows: They would be accessed as follows: widget.partnum = "123A"; widget.partnum = "123A"; widget.description = "iron widget"; widget.description = "iron widget"; widget.pricing.wholesale = 100.0; widget.pricing.wholesale = 100.0; widget.pricing.retail = 150.0; widget.pricing.retail = 150.0;
  • 16.
    Arrays of Structures Arraysof Structures  Because Because structures structures can can hold several items of varying data types hold several items of varying data types, a , a single single array of structures array of structures can be used can be used in place of several arrays of regular variables in place of several arrays of regular variables. .  An An array of structures array of structures is defined like any other array. is defined like any other array.  Assume the following structure declaration exists in a program: Assume the following structure declaration exists in a program: struct BookInfo { struct BookInfo { char title[100]; char title[100]; char author[50]; char author[50]; char publisher[100]; char publisher[100]; double price; double price; }; };  The following statement The following statement defines an array defines an array, , bookList bookList, which has , which has 20 elements 20 elements. .  Each Each element element is a is a BookInfo structure BookInfo structure. . BookInfo bookList[20]; BookInfo bookList[20];
  • 17.
     Each element Eachelement of the of the array array may be accessed through a may be accessed through a subscript subscript. .  For example, For example, bookList[0] bookList[0] is the is the first structure in the array first structure in the array, , bookList[1] bookList[1] is the is the second second, , and so forth. and so forth.  To To access a member of any element access a member of any element, simply , simply place the dot operator place the dot operator and and member name member name after after the the subscript subscript. .  For example, the following expression refers to the For example, the following expression refers to the title title member of member of bookList[5] bookList[5]: : bookList[5].title bookList[5].title  The following The following loop loop steps through the array steps through the array, displaying the information stored in each , displaying the information stored in each element: element: for (int index = 0; index < 20; index++) { for (int index = 0; index < 20; index++) { cout << bookList[index].title << endl; cout << bookList[index].title << endl; cout << bookList[index].author << endl; cout << bookList[index].author << endl; cout << bookList[index].publisher << endl; cout << bookList[index].publisher << endl; cout << bookList[index].price << endl << endl; cout << bookList[index].price << endl << endl; } }
  • 18.
    struct BookInfo { structBookInfo { char title[100]; char title[100]; char author[50]; char author[50]; char publisher[100]; char publisher[100]; double price; double price; }; };  Note: Note: Because the members Because the members title title, , author author, and , and publisher publisher are are character objects character objects, their , their individual elements individual elements can be accessed as well. can be accessed as well.  The following statement displays the The following statement displays the first character first character of the of the title title member of member of bookList[10] bookList[10]: : cout << bookList[10].title[0]; cout << bookList[10].title[0];  And the following statement stores the character And the following statement stores the character ‘t’ ‘t’ in the in the fourth fourth position position of the of the publisher publisher member of member of bookList[2] bookList[2]: : bookList[2].publisher[3] = 't'; bookList[2].publisher[3] = 't';
  • 19.
     // Thisprogram uses an array of structures to hold employee payroll data. struct PayInfo { int hours; // Hours worked double payRate; // Hourly pay rate }; int main () { const int NUM_EMPS = 5; int index; PayInfo workers[NUM_EMPS]; // Define an array of structures double grossPay; cout << "Enter the hours worked and hourly pay rates of " << NUM_EMPS << " employees. n"; for (index = 0; index < NUM_EMPS; index++) { cout << "Hours worked by employee #" << (index + 1) << ": "; cin >> workers[index].hours; cout << "Hourly pay rate for employee #" << (index + 1) << ": "; cin >> workers[index].payRate; } cout << "nHere is the gross pay for each employee:n"; for (index = 0; index < NUM_EMPS; index++) { grossPay = workers[index].hours * workers[index].payRate; cout << "Employee #" << (index + 1) << ": $" << setw(7) << grossPay << endl; } }
  • 20.