Lab: Title: Lab Objectives:: Variable Definition Information Held
Lab: Title: Lab Objectives:: Variable Definition Information Held
As an example, suppose you want to create a program to simulate a calendar. The program may
contain the following ADTs: year, month, and day. Note that month could take on values January,
February. . . December or even 1, 2. . . 12 depending on the wishes of the programmer. Likewise,
the range of values for day could be Monday, Tuesday. . . Sunday or even 1, 2 . . . 7. There is much
more flexibility in the choice of allowable values for year. If the programmer is thinking short term
they may wish to restrict year to the range 1990–2010. Of course there are many other possibilities.
In this lab we study the structure. Like arrays, structures allow the programmer to group data
together. However, unlike an array, structures allow you to group together items of different data
types. To see how this could be useful in practice, consider what a student must do to register for a
college course. Typically, one obtains the current list of available courses and then selects the
desired course or courses. The following is an example of a course you may choose:
Note that there are four items related to this course: the course discipline (CHEM), the course
number (310), the course title (Physical Chemistry), and the number of credit hours (4). We could
define variables as follows:
All of these variables are related because they can hold information about the same course. We can
package these together by creating a structure. Here is the declaration:
1
struct course
{
char discipline[5];
int courseNumber;
char courseTitle[21];
short credits;
}; //note the semi-colon here
The tag is the name of the structure, course in this case. The tag is used like a data type name. Inside
the braces we have the variable declarations that are the members of the structure. So the code
above declares a structure named course which has four members: discipline, courseNumber,
courseTitle, and credits.
The programmer needs to realize that the structure declaration does not define a variable. Rather it
lets the compiler know what a course structure is composed of. That is, the declaration creates a new
data type called course. We can now define variables of type course as follows:
course pChem;
course colonialHist;
Both pChem and colonialHist will contain the four members previously listed. We could have also
defined these two structure variables on a single line:
Both pChem and colonialHist are called instances of the course structure. In other words, they are
both user defined variables that exist in computer memory. Each structure variable contains the four
structure members.
Certainly the programmer will need to assign the members values and also keep track of what
values the members have. C++ allows you to access structure members using the dot operator.
Consider the following syntax:
colonialHist.credits = 3;
In this statement the integer 3 is assigned to the credits member of colonialHist. The dot operator is
used to connect the member name to the structure variable it belongs to. Now let us put all of these
ideas together into a program. The sample program in file: lab8sample1.cpp uses the course
structure just described. This interactive program allows a student to add requested courses and
keeps track of the number of credit hours for which they have enrolled. The execution is controlled
by a do-while loop.
Make sure that you understand the logic of this program and, in particular, how structures are used.
Notice the line at the end of the while loop that reads
2
while(toupper(addclass) == 'Y');
As a second example, suppose we would like a simple program that computes the area and
circumference of two circles input by the user. Although we can easily do this using previously
developed techniques, let us see how this can be done using structures. We will also determine
which circle’s center is further from the origin.
Arrays of Structures
In the previous sample program we were interested in two instances of the circle structure. What if
we need a much larger number, say 100, instances of this structure? Rather than define each one
separately, we can use an array of structures. An array of structures is defined just like any other
array. For example suppose we already have the following structure declaration in our program:
struct circle
{
float centerX; // x coordinate of center
float centerY; // y coordinate of center
float radius;
float area;
float circumference;
float distance_from_origin; // distance of center from
origin
};
Then the following statement defines an array, circn, which has 100 elements. Each of these
elements is a circle structure variable:
circle circn[100];
Like the arrays encountered in previous lessons, you can access an array element using its subscript.
So circn[0] is the first structure in the array, circn[1] is the second, and so on. The last structure in
the array is circn[99]. To access a member of one of these array elements, we still use the dot
operator. For instance, circn[9].circumference gives the circumference member of circn[9]. If we
want to display the center and distance from the origin of the first 30 circles we can use the
following:
When studying arrays you may have seen two-dimensional arrays which allow one to have “a
3
collection of collections” of data. An array of structures allows one to do the same thing. However,
we have already noted that structures permit you to group together items of different data type,
whereas arrays do not. So an array of structures can sometimes be used when a two-dimensional
array cannot.
Initializing Structures
We have already seen numerous examples of initializing variables and arrays at the time of their
definition in the previous labs. Members of structures can also be initialized when they are defined.
Suppose we have the following structure declaration in our program:
struct course
{
char discipline[5];
int courseNumber;
char courseTitle[21];
short credits;
};
The values in this list are assigned to course’s members in the order they appear. Thus, the string
"HIST" is assigned to colonialHist.discipline, the integer 302 is assigned to
colonialHist.courseNumber, the string "Colonial History" is assigned to colonialHist.courseTitle,
and the short value 3 is assigned to colonialHist.credits. It is not necessary to initialize all the
members of a structure variable. For example, we could initialize just the first member:
This statement leaves the last three members uninitialized. We could also initialize only the first two
members:
There is one important rule, however, when initializing structure members. If one structure member
is left uninitialized, then all structure members that follow it must be uninitialized. In other words,
we cannot skip members of a structure during the initialization process.
It is also worth pointing out that you cannot initialize a structure member in the declaration of the
structure. The following is an illegal declaration:
4
char courseTitle[20] = "Colonial History"; //
illegal
short credits = 3; // illegal
};
If we recall what a structure declaration does, it is clear why the above code is illegal. A structure
declaration simply lets the compiler know what a structure is composed of. That is, the declaration
creates a new data type (called course in this case). So the structure declaration does not define any
variables. Hence there is nothing that can be initialized there.
Often it is useful to nest one structure inside of another structure. Consider the consider code in the
file:lab8sample3.cpp. Note that the programs in this lesson so far have not been modularized.
Everything is done within the main function. In practice, this is not good structured programming. It
can lead to unreadable and overly repetitious code. To solve this problem, we need to be able to
pass structures and structure members to functions. In this next section, you will see how to do this.
Just as we can use other variables as function arguments, structure members may be used as
function arguments. Consider the following structure declaration:
struct circle
{
float centerX; // x coordinate of center
float centerY; // y coordinate of center
float radius;
float area;
};
Suppose we also have the following function definition in the same program:
float computeArea(float r)
{
return PI * r * r; // PI must previously be defined as a
// constant float
}
Let firstCircle be a variable of the circle structure type. The following function call passes
firstCircle.radius into r. The return value is stored in firstCircle.area:
firstCircle.area = computeArea(firstCircle.radius);
It is also possible to pass an entire structure variable into a function rather than an individual
member.
5
struct course
{
char discipline[5];
int courseNumber;
char courseTitle[21];
short credits;
};
course pChem;
Suppose the following function definition uses a course structure variable as its parameter:
void displayInfo(course c)
{
cout << c.discipline << endl;
cout << c.courseNumber << endl;
cout << c.courseTitle << endl;
cout << c.credits << endl;
}
displayInfo(pChem);
There are many other topics relating to functions and structures such as returning a structure from a
function and pointers to structures. Although we do not have time to develop these concepts in this
lab, the text does contain detailed coverage of these topics for the interested programmer.
6
Pre-lab
1. The name of a structure is called the ______________________.
2. An advantage of structures over arrays is that structures allow one to use
_______________ items of data types, whereas arrays do not.
3. One structure inside of another structure is an example of a _____________________ .
4. The variables declared inside the structure declaration are called the
___________________ of the structure.
5. When initializing structure members, if one structure member is left uninitialized, then all
the structure members that follow must be____________________.
6. A user defined data type is often an ________________________.
7. Once an array of structures has been defined, you can access an array
____________________ element using its __________________.
8. The ________________________ allows the programmer to access structure members.
9. You may not initialize a structure member in the _________________________.
10. Like variables, structure members may be used as ___________________ arguments.
7
Lab 1: Working with Basic Structures
Retrieve program lab8a.cpp from the exercises directory in lab 8 and perform the tasks:
Exercise 2: Add code to the program above so that the modified program will determine whether
or not the rectangle entered by the user is a square.
Sample Run:
Enter the length of a rectangle: 7
Enter the width of a rectangle: 7
The area of the rectangle is 49.00
The perimeter of the rectangle is 28.00
The rectangle is a square.
Exercise 1: Fill in the code as indicated by the comments with three forward slashes.
Sample Run:
Please input the yearly income for Tim McGuiness: 30000
Name: Tim McGuiness
Social Security Number: 255871234
Taxes due for this year: $10500.00
Sample Run:
Enter this year’s income for tax payer 1: 45000
Enter the tax rate for tax payer # 1: .19
Enter this year’s income for tax payer 2: 60000
8
Enter the tax rate for tax payer # 2: .23
Enter this year’s income for tax payer 3: 12000
Enter the tax rate for tax payer # 3: .01
Enter this year’s income for tax payer 4: 104000
Enter the tax rate for tax payer # 4: .30
Enter this year’s income for tax payer 5: 50000
Enter the tax rate for tax payer # 5: .22
Exercise 2: Modify the program above by adding a third structure named results which has two
members area and perimeter. Adjust the rectangle structure so that both of its members are
structure variables.
Exercise 3: Modify the program above by adding functions that compute the area and perimeter.
The structure variables should be passed as arguments to the functions.
Sample Run:
Enter the length of a rectangle: 9
Enter the width of a rectangle: 6
The area of the rectangle is 54.00
The perimeter of the rectangle is 30.00
9
Lab Assignments:
1. Array of Structures
Re-write Sample Program in lab8sample2.cpp so that it works for an array of structures. Write
the program so that it compares 6 circles. You will need to come up with a new way of
determining which circle’s center is closest to the origin. Use file lab8assignment1.cpp to test
and submit your solution.
2. Flight management
Write a program that uses a structure to store the following information for a particular month at
the local airport:
The program should have an array of twelve structures to hold travel information for the entire
year. The program should prompt the user to enter data for each month. Once all data is entered,
the program should calculate and output the average monthly number of landing planes, the
average monthly number of departing planes, the total number of landing and departing planes
for the year, and the greatest and least number of planes that landed on any one day (and which
month it occurred in). Use file lab8assignment2.cpp to test and submit your solution.
10