You are on page 1of 7

LAB 13

STRUCTURES IN C++

13.1 OBJECTIVES

- Introduction to structures
- How to access the members of a structure
- Nested structures
- Pointer to structures

13.2 PRE-LAB READING

Variables of type float, char, and int represent one item of information: a height, an amount, a count,
and so on. But just as groceries are organized into bags, employees into departments, and words into
sentences, it’s often convenient to organize simple variables into more complex entities. The C++
construction called the structure is one way to do this.

13.2.1 STRUCTURES
A structure is a collection of simple variables. These variables can be of different fundamental types:
Some can be int, some can be float, and so on. Structures can be used to hold records from a database
or to store information about contacts in an address book.
The syntax to define a structure is as follows:
struct tag {
data_type1 member_name1;
data_type2 member_name2;
data_type3 member_name3;
.
.
}; Don’t forget to place a
semicolon here.

Where tag is a name for the structure, decided by the programmer. Within braces {}, there is a list
with the data members, each one is specified with a type and a valid identifier as its name. For example:

1 struct product {
2 int weight;
3 double price;
4 } ;
5 .
6 .
.

1
.
.
product apple; //somewhere in main()
product banana, melon;

This declares a structure type, called product, and defines it having two members: weight and
price, each of a different fundamental type. This declaration creates a new type (product), which is
then used to declare three objects (structure variables) of this type:
apple, banana, and melon in main of the program. Alternatively,
you can declare these objects immediately after the ending brace of
structure definition as follows: Memory allocation take place
struct tag {
data_type1 member_name1;
only at the time of structure
data_type2 member_name2; variables declaration. Defining
data_type3 member_name3; structure does not reserve any
.
. memory, it only serves as a
}apple, banana, melon; template.

Note: Remember that it is different than an array in a sense that arrays can only be used to store
multiple data items of same kind.

13.2.2 HANDLING STRUCTURE MEMBERS & VARIABLES

After defining a structure its members can be accessed by using (.) dot operator/member access
operator.
 One can set the values for data members of any structure using dot operator like this:
apple.weight = 2;
apple.price = 60; //or

cin>>apple.weight;
cin>>apple.price;

 Data members of a structure are treated just like other variables like you see in above
statements that the value has given to the members by simply using the assignment operator.
 One can initialize all the members of any structure variable at once as follows:
product melon = {5 , 80};
cout<<melon.weight<<endl; // output 5
cout<<melon.price<<endl; // output 80

 Two structure variables of identical type can exchange values same as two variables of identical
data type e.g
melon = apple;
cout<<melon.weight<<endl; // output 2
cout<<melon.price<<endl; // output 60

2
Activity 1
Create a structure named as complex_number having data members “real” and “imag”. Ask
user to enter both real and imaginary parts for a complex number. Compute the conjugate for
that particular number and show it to the user.
Note: Conjugate of a complex number is the number with equal real part and imaginary part
equal in magnitude but opposite in sign.

13.2.3 NESTED STRUCTURES

When a structure contains another structure, it is called nested structure. You can nest a structure in
following way:
struct structure1
{
- - - - - - - - - -
- - - - - - - - - -
};

struct structure2
{
- - - - - - - - - -
- - - - - - - - - -
structure1 var;
};

To have better idea, let’s consider a structure that stores the dimensions of a typical room: its length
and width. These dimensions are further measured in feet and inches so we need another structure
named as Distance having a composition like this.
struct Distance
{
int feet;
float inches;
};
/////////////////////////////////////////
struct Room
{
Distance length;
Distance width;
};
////////////////////////////////////////
int main()
{
Room dining; //declaration of room variable, memory reserved
dining.length.feet = 13; //assign values to members
dining.length.inches = 6.5;
dining.width.feet = 10;
dining.width.inches = 0.0;
- - - -
- - - -
- - - -
return 0;
}

3
Because one structure (Distance) is nested inside another (Room), we must apply the dot operator
twice to access the structure members.
dining.length.feet = 13;

The statement means “take the feet member of the length member of the variable dining and assign it
the value 13. Hence, we can easily access a particular data member by using the dot operator according
to the levels of nesting.

Activity 2

Start with above example and perform addition to calculate the total length and width in feet. Also
calculate the area of dining room and display it on the screen.

13.2.4 POINTER TO STRUCTURES

A pointer variable can be created not only for in built data types but they can also be created for user
defined types like structure. For example consider the Distance structure again:
struct Distance
{
int feet;
float inches;
};
int main()
{
Distance var, *ptr; //declaration of a structure variable and a pointer to the same structure
ptr=&var;
(*ptr).feet= 5; //accessing data member of “var” through pointer
(*ptr).inches=2.5; //equivalent to var.inches=2.5;
return 0;
}

Notice that we have placed *ptr into braces which is not by the way. Writing this statement as *ptr.feet
will cause an error because (.) operator has more precedence than (*) operator. To avoid this vague
syntax C++ introduces arrow operator (->) which works for the same purpose.
ptr->feet=5; //accessing data member of Distance
through pointer directly
ptr->inches=2.5;
Do not forget the size of
Moreover, you can also allocate structure values dynamically, using structure variable varies,
the new operator as: depending on the data
Distance *dptr= new Distance; members it has, but pointer
to any structure occupies
same memory space.

4
13.2.5 PASSING STRUCTURES TO FUNCTIONS
Like other basic data types, structures can also be passed as an argument to a function. Pointers to
structure can also be used as an argument to function in a similar way.
struct Distance
{
int feet;
float inches;
};

void display( Distance dd );


///////////////////////////////////////////////////////////////
int main()
{
Distance d1;
cout<<”Enter feet: ”<<endl;
cin>>d1.feet;
cout<<”Enter inches: ”<<endl;
cin>>d1.inches;
display(d1);
return 0;
}
//////////////////////////////////////////////////////////////
void display( Distance dd ) //parameter dd of type Distance
{
cout << dd.feet << “\’-” << dd.inches << “\””;
}

This example elaborates how structures passed to functions which is very similar as arguments of other
data types.

Activity 3:

Write a structure which holds student name, student id, and marks in 3 subjects (Programming, English,
and Pak-Studies). Pass this structure to a function which will compute the total marks and assign grade
according to the following policy:
Grade A: 90% or above
Grade B: 75% above and below 90%
Grade C: 60% above and below 75 %
Fail: 60% below

5
13.3 LAB TASKS

1. When you dial a phone number such as 042-7932-1234, you are actually contacting the person
by dialing his/her city code (042), area code (1932) and the actual number (1234). Write a
program that uses structure to store these parts of a contact. Declare 2 structure variables mine
and yours and initialize mine with respective details. Now ask the user to enter the same details
and display both the contacts back on the screen. (25 marks)

2. Assume that you are performing an experiment in laboratory and you need to be extra careful
regarding the execution time for experiment. Create a structure Time to keep the record of
hours, minutes and seconds. Feed the start and stop time of your experiment to your program
and it must display the exact amount of time consumed for experiment. Create a function to
calculate the difference between start and stop points. Your function should take pointers to
structure as an argument. (25 marks)

3. A point on the two-dimensional plane can be represented by two numbers: an x coordinate and
a y coordinate. For example, (-3,5) represents a point 3 units to the left of the vertical axis, and 5
units up from the horizontal axis. The sum of two points can be defined as a new point whose x
coordinate is the sum of the x coordinates of the two points, and whose y coordinate is the sum
of the y coordinates.
Write a program that uses a structure called point to model a point. Define three points, and
have the user input values to two of them. Then set the third point equal to the sum of the
other two, and display the value of the new point. Your program should also give the
information of respective quadrant in which a point exists. (25 marks)

4. Suppose you have hired 5 employees for your company after signing a contract. Now you have
to assign a specific employee code to them for identification. Write a program which will
generate employee codes for each member. Create two structures named as employee and
address in such a way that employee should have a data member of type address. Declare at
least 5 employee variables and feed the following information into your system:
Employee Name
Employee Age
Decided Salary
House #
Name of City
Postal Code
Choose the appropriate data members for each structure and generate a 4 digit random code
for every single worker. Display it back to the user with all the above details. (25 marks)

6
13.4 POST-LAB ACTIVITY
1. Write a grading program for a class with the following grading policies:
a. There are two quizzes, each graded on the basis of 10 points.
b. There is one midterm exam and one final exam, each graded on the basis of 100 points.
c. The final exam counts for 50% of the grade, the midterm counts for 25%, and the two quizzes
together count for a total of 25%. (Do not forget to normalize the quiz scores. They should be
converted to a percent before they are averaged in.)
Any grade of 90 or more is an A, any grade of 80 or more (but less than 90) is a B, any grade of
70 or more (but less than 80) is a C, any grade of 60 or more (but less than 70) is a D, and any
grade below 60 is an F. The program will read in the student’s scores and output the student’s
record, which consists of two quiz and two exam scores as well as the student’s average numeric
score for the entire course and the final letter grade. Define and use a structure for the student
record.

2. Use structures to model a playing card game. This program imitates a game played by
cardsharps at carnivals. The cardsharp shows you three cards, then places them face down on
the table and interchanges their positions several times. If you can guess correctly where a
particular card is, you win. Everything is in plain sight, yet the cardsharp switches the cards so
rapidly and confusingly that the player (the mark) almost always loses track of the card and loses
the game, which is, of course, played for money. The format of structure will be:
struct card
{
int number;
int suit;
};

The number runs from 2 to 14, where 11, 12, 13, and 14 represent the jack, queen, king, and
ace, respectively. The suit runs from 0 to 3, where these four numbers represent clubs,
diamonds, hearts, and spades.

You might also like