Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 20

CHAPTER-7

STRUCTURES
STRUCTURES
 C++ allows you to group a set of variables together into a single item
known as a structure.
 A structure is a set of diverse types of data grouped together under a
unique declaration.
 C++ gives you the ability to create a relationship between variables
by packaging them together into a structure
 A structure bundles together items that logically belong together.
 The members of a structure are attributes describing same object.
 For example, a payroll system might keep the variables shown in the
following table.
 All of the variables
listed in this table
are related
because they can
hold data about the
same employee.
STRUCTURES
 Before a structure can be used, it must be declared. Here is the
general format of a structure declaration:
struct tag // Structure declaration begins with the key word struct and a name.
{
// Variable declarations go here.
}; // Notice the required semi-colon.
 The tag is the name of the structure. It is used like a data type
name.
 The variable declarations that appear inside the braces declare
the members of the structure.
 Here is an example of a structure declaration that holds the payroll
data listed in table above:
struct PayRoll
{
int empNumber;
char name[30];
double hours,
payRate,
grossPay;
};
STRUCTURES
 The structure declaration in our example creates
a new data type named PayRoll.
 Once the data type has been created you can
define variables of this type with simple definition
statements.
 For example, the following statement defines a
variable called deptHead:
PayRoll deptHead;
 The data type of deptHead is a PayRoll structure.
 The structure tag, PayRoll, is placed before the
variable name just as the word int or double would
be to define variables of those types.
STRUCTURES
 Structure variables contain other variables known as
members.
 Because deptHead is a PayRoll structure, it contains the
five members listed in the Pay-Roll structure declaration.
 This is illustrated in the following figure.
STRUCTURES
 Just as it’s possible to define multiple int or double
variables, it’s possible to define multiple structure
variables in a program.
 The following statement defines three PayRoll variables:
deptHead, foreman, and associate.
PayRoll deptHead, foreman, associate;
 The following figure illustrates the existence of these
three variables.
STRUCTURES
 Each of these variables is a separate instance of the
PayRoll structure with its own memory allocated to hold
its members.
 Each structure variable contains members with the same
name.
 Here are some other examples of structure declarations
and variable definitions:

// Structure declaration // Structure declaration


struct Time struct Date
{ {
int hours, minutes, int day, month, year;
seconds; };
}; // Definition of two Date structure variables
// Definition of a Time structure variable. Date today, yesterday;
Time now;
Accessing Structure Members
 C++ provides the dot operator (a period) to access the
individual members of a structure.
 Using our example of deptHead as a PayRoll structure
variable, the following statement demonstrates how to
access the empNumber member:
deptHead.empNumber = 475;
 In this statement, the number 475 is assigned to the
empNumber
 The dot operator connects the name of the member with
the name of the structure variable it belongs to.
 For example, the following statements display the
contents of deptHead’s members:
cout << deptHead.empNumber << endl;
cout << deptHead.name << endl;
cout << deptHead.hours << endl;
cout << deptHead.payRate << endl;
cout << deptHead.grossPay << endl;
Displaying and Comparing Structure Variables
 In each member of the employee structure variable is
displayed separately.
 Entire contents of a structure variable cannot be
displayed by simply passing the whole variable to cout.
 For example, the following statement will not work.
cout << employee << endl; // Error!
 You cannot perform comparison operations on entire
structure variables.
 For example, if employee1 and employee2 are both Payroll
structure variables, this comparison will cause an error.
if (employee1 == employee2) // Error!
 The following comparison is perfectly legal.
if (employee1.hours == employee2.hours) // Legal
 The following program segment illustrates how they can be passed as arguments to functions
and can be compared.
struct Circle // Declare what a Circle structure looks like
{
double radius;
double diameter;
double area;
};
const double PI = 3.14159;
main()
{
Circle c1, c2; // Define 2 Circle structure variables
cout << "Enter the diameter of circle 1 and circle 2: : ";
cin >> c1.diameter >> c2.diameter;
c1.radius = c1.diameter / 2;
c1.area = PI * pow(c1.radius, 2.0);
c2.radius = c2.diameter / 2;
c2.area = PI * pow(c2.radius, 2.0);
cout << "\nThe radius and area of the circles are\n";
cout << "Circle 1 -- Radius: " << c1.radius<< " Area: " << c1.area << endl;
cout << "Circle 2 -- Radius: " << c2.radius<< " Area: " << c2.area << endl;
if (c1.area == c2.area)
cout << "The two circles have the same area.\n\n";
}
Initializing a Structure
 The members of a structure variable can be
initialized with an initialization list.
 The items in the list are separated by commas and
surrounded by braces.
 Suppose, for example, the following Date structure
has been declared:
struct Date
{
int day, month, year;
};
 A Date variable can now be defined and initialized by
following the variable name with the assignment
operator and an initialization list, as shown here:
Date birthday = {23, 8, 1983};
Initializing a Structure
Date birthday = {23, 8, 1983};
 This statement defines birthday to be a variable which is a Date
structure.
 The values following the definition are assigned to its members in
order.
 So birthday has been initialized as follows:

 If we know the birthday to be stored is August 23, but do


not know the year, the variable could be defined and
initialized like this:
Date birthday = {23, 8);
Initializing a Structure
 C++ does not provide a way to skip members when
using an initialization list.
 If you leave a structure member uninitialized, however, you must
leave all the members that follow it uninitialized as well.
 The following statement, which attempts to skip the initialization
of the month member, is not legal.
Date birthday = {23, , 1983); // Illegal!
 You cannot initialize a structure member in the declaration of the
structure.
 For example, the following declaration is illegal:
// Illegal structure declaration
struct Date
{
int day = 23,
month = 8,
year = 1983;
};
Nested Structures
 It is possible for a structure variable to be a member of another
It is possible for a structure variable to be a member of another
structure variable.
 When some of the attributes are related and form a logical subgroup
of the object’s attributes, it is possible to bundle them together and
use a nested structure.
 For example, consider the following structure declarations:
struct Costs
{
double wholesale;
double retail;
};
struct Item
{
char partNum[30];
char description[30];
Costs pricing;
};
 The Costs structure has two double members, wholesale and retail.
 The Item structure has three members.
 The first two, partNum and description, are character objects.
 The third, pricing, is a nested Costs structure.
Nested Structures
 Assume variable widget is defined to be an Item structure:
Item widget;
 The following figure illustrates its members.

 They would be accessed as follows:


widget.partnum = "123A";
widget.description = "iron widget";
widget.pricing.wholesale = 100.0;
widget.pricing.retail = 150.0;
Arrays of Structures
 Because structures can hold several items of varying
data types, a single array of structures can be used in
place of several arrays of regular variables.
 An array of structures is defined like any other array.
 Assume the following structure declaration exists in a
program:
struct BookInfo
{
char title[100];
char author[50];
char publisher[100];
double price;
};
 The following statement defines an array, bookList,
which has 20 elements.
 Each element is a BookInfo structure.
BookInfo bookList[20];
 Each element of the array may be accessed through a subscript.
 For example, bookList[0] is the first structure in the array,
bookList[1] is the second, and so forth.
 To access a member of any element, simply place the dot operator
and member name after the subscript.
 For example, the following expression refers to the title member
of bookList[5]:
bookList[5].title
 The following loop steps through the array, displaying the
information stored in each element:
for (int index = 0; index < 20; index++)
{
cout << bookList[index].title << endl;
cout << bookList[index].author << endl;
cout << bookList[index].publisher << endl;
cout << bookList[index].price << endl << endl;
}
struct BookInfo
{
char title[100];
char author[50];
char publisher[100];
double price;
};
 Note: Because the members title, author, and publisher
are character objects, their individual elements can be
accessed as well.
 The following statement displays the first character of the title
member of bookList[10]:
cout << bookList[10].title[0];
 And the following statement stores the character ‘t’ in the fourth
position of the publisher member of bookList[2]:
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

You might also like