Handouts For Lab 8
Handouts For Lab 8
Computer Programming
Handouts for Lab 8
Structures in C++
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
Introduction:
C++ provides another structured data type, called a struct (some languages use the term
‘‘record’’), to group related items of different types. An array is a homogeneous data structure; a
struct is typically a heterogeneous data structure.
Structures:
Suppose that you want to write a program to process student data. A student record consists of,
among other things, the student’s name, student ID, GPA, courses taken, and course grades.
Thus, various components are associated with a student. However, these components are all of
different types. For example, the student’s name is a string, and the GPA is a floating-point
number. Because these components are of different types, you cannot use an array to group all of
the items associated with a student. C++ provides a structured data type called struct to group
items of different types. Grouping components that are related but of different types offers
several advantages. For example, a single variable can pass all the components as parameters to a
function.
struct: A collection of a fixed number of components in which the components are accessed
by name. The components may be of different types.
The components of a struct are called the members of the struct. The general syntax of a
struct in C++ is:
struct structName
{
dataType1 identifier1;
dataType2 identifier2;
.
.
.
dataTypen identifiern;
};
In C++, struct is a reserved word. The members of a struct, even though they are enclosed
in braces (that is, they form a block), are not considered to form a compound statement. Thus, a
semicolon (after the right brace) is essential to end the struct statement. A semicolon at the
end of the struct definition is, therefore, a part of the syntax.
The statement:
struct houseType
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
{
string style;
int numOfBedrooms;
int numOfBathrooms;
int numOfCarsGarage;
int yearBuilt;
int finishedSquareFootage;
double price;
double tax;
};
defines a struct houseType with 8 members. The member style is of type string, the
members numOfBedrooms, numOfBathrooms, numOfCarsGarage, yearBuilt, and
finishedSquareFootage are of type int, and the members price and tax are of type
double. Like any type definition, a struct is a definition, not a declaration. That is, it defines
only a data type; no memory is allocated. Once a data type is defined, you can declare variables
of that type. For example, the following statement defines newHouse to be a struct variable of
type houseType:
//variable declaration
houseType newHouse;
structVariableName.memberName
struct studentType
{
string firstName;
string lastName;
char courseGrade;
int testScore;
int programmingScore;
double GPA;
};
//variables
studentType newStudent;
studentType student;
Suppose you want to initialize the member GPA of newStudent to 0.0. The following
statement accomplishes this task:
newStudent.GPA = 0.0;
newStudent.firstName = "John";
newStudent.lastName = "Brown";
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
store "John" in the member firstName and "Brown" in the member lastName of
newStudent. After the preceding three assignment statements execute, newStudent is as
shown in Figure 2.
The statement:
reads the next string from the standard input device and stores it in:
newStudent.firstName
The statement:
reads two integer values from the keyboard and stores them in newStudent.testScore and
newStudent.programmingScore, respectively.
newStudent.courseGrade = 'A';
newStudent.courseGrade = 'B';
newStudent.courseGrade = 'C';
newStudent.courseGrade = 'D';
else
newStudent.courseGrade = 'F';
Example 1:
Write a program to input data into and then print data from the members of the structure.
#include <cstdlib>
#include <iostream>
using namespace std;
struct address
{
char city [15];
int pcode;
};
Example 2:
Write a program to copy one structure variable to another variable and then to print it on the
screen.
#include <cstdlib>
#include <iostream>
using namespace std;
struct abc
{
char name [15];
int age;
};
return EXIT_SUCCESS;
}
struct address
{
char city[15];
int pcode;
};
address taq = {“Lahore”, 54500};
Assignment:
We can assign the value of one struct variable to another struct variable of the same type
by using an assignment statement. Suppose that newStudent is as shown in Figure 3.
The statement:
student = newStudent;
copies the contents of newStudent into student. After this assignment statement executes,
the values of student are as shown in Figure 4.
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
student = newStudent;
student.firstName = newStudent.firstName;
student.lastName = newStudent.lastName;
student.courseGrade = newStudent.courseGrade;
student.testScore = newStudent.testScore;
student.programmingScore = newStudent.programmingScore;
student.GPA = newStudent.GPA;
student.lastName == newStudent.lastName)
Although you can use an assignment statement to copy the contents of one struct into
another struct of the same type, you cannot use relational operators on struct variables.
Therefore, the following would be illegal:
Input /Output:
No aggregate input/output operations are allowed on a struct variable. Data in a struct
variable must be read one member at a time. Similarly, the contents of a struct variable must
be written one member at a time. We have seen how to read data into a struct variable. Let us
now see how to output a struct variable. The statement:
Arrays in structs:
A list is a set of elements of the same type. Thus, a list has two things associated with it: the
values (that is, elements) and the length. Because the values and the length are both related to a
list, we can define a struct containing both items.
listType intList;
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
The variable intList has two members: listElem, an array of 1000 components of type
int, and listLength, of type int. Moreover, intList.listElem accesses the member
listElem, and intList.listLength accesses the member listLength.
intList.listLength = 0; //Line 1
intList.listLength++; //Line 3
intList.listLength++; //Line 5
The statement in Line 1 sets the value of the member listLength to 0. The statement in Line
2 stores 12 in the first component of the array listElem. The statement in Line 3 increments
the value of listLength by 1. The meaning of the other statements is similar.
structs in Arrays:
Suppose a company has 50 full-time employees. We need to print their monthly paychecks and
keep track of how much money has been paid to each employee in the year-to-date. First, let’s
define an employee’s record:
struct employeeType
{
string firstName;
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
string lastName;
int personID;
string deptID;
double yearlySalary;
double monthlySalary;
double yearToDatePaid;
double monthlyBonus;
};
Each employee has the following members (components): first name, last name, personal ID,
department ID, yearly salary, monthly salary, year-to-date paid, and monthly bonus.
Because we have 50 employees and the data type of each employee is the same, we can use an
array of 50 components to process the employees’ data.
employeeType employees[50];
This statement declares the array employees of 50 components of type employeeType (see
Figure 7). Every element of employees is a struct.
struct employeeType
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
string firstname;
string middlename;
string lastname;
string empID;
string address1;
string address2;
string city;
string state;
string zip;
int hiremonth;
int hireday;
int hireyear;
int quitmonth;
int quitday;
int quityear;
string phone;
string cellphone;
string fax;
string pager;
string email;
string deptID;
double salary;
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
};
As you can see, a lot of information is packed into one struct. This struct has 22 members.
Some members of this struct will be accessed more frequently than others, and some
members are more closely related than others. Moreover, some members will have the same
underlying structure. For example, the hire date and the quit date are of the date type int. Let us
reorganize this struct as follows:
struct nameType
{
string first;
string middle;
string last;
};
struct addressType
{
string address1;
string address2;
string city;
string state;
string zip;
};
struct dateType
{
int month;
int day;
int year;
};
struct contactType
{
string phone;
string cellphone;
string fax;
string pager;
string email;
};
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
We have separated the employee’s name, address, and contact type into subcategories.
Furthermore, we have defined a struct dateType. Let us rebuild the employee’s record as
follows:
struct employeeType
nameType name;
string empID;
addressType address;
dateType hireDate;
dateType quitDate;
contactType contact;
string deptID;
double salary;
};
The information in this employee’s struct is easier to manage than the previous one. Some
of this struct can be reused to build another struct. For example, suppose that you
want to define a customer’s record. Every customer has a first name, last name, and middle
name, as well as an address and a way to be contacted. You can, therefore, quickly put together a
customer’s record by using the structs nameType, addressType, contactType,
and the members specific to the customer. Next, let us declare a variable of type
employeeType and discuss how to access its members.
employeeType newEmployee;
The statement:
newEmployee.salary = 45678.00;
newEmployee.name.first = "Mary";
newEmployee.name.middle = "Beth";
newEmployee.name.last = "Simmons";
set the first, middle, and last name of newEmployee to "Mary", "Beth", and
"Simmons", respectively. Note that newEmployee has a member called name. We access
this member via newEmployee.name. Note also that newEmployee.name is a struct and
has three members. We apply the member access criteria to access the member first of the struct
newEmployee.name. So, newEmployee.name.first is the member where we store the
first name.
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
The statement:
The following statement declares employees to be an array of 100 components, wherein each
component is of type employeeType:
employeeType employees[100];
>> employees[j].name.last;
reads and stores the names of 100 employees in the array employees. Because employees is an
array, to access a component, we use the index. For example, employees[50] is the 51st
component of the array employees(recall that an array index starts with 0). Because
employees[50] is a struct, we apply the member access criteria to select a particular
member.
*********************************