STRUCTURES
SCHOOL OF COMPUTING Bennett M. Tanyag
DEFINITION OF A STRUCTURE
• A structure (or a record) is a collection of
variables of different types that are
referenced under one name.
• It is a way of treating a diverse collection of
data types as a single entity.
• An array is a homogeneous data structure; a
struct is typically a heterogeneous data
structure.
Structures
DEFINITION OF A STRUCTURE
• The format of a structure template is:
struct structure_name
{
type member_name1;
type member_name2;
type member_name3;
.
.
.
type member_nameN;
};
Structures
DEFINITION OF A STRUCTURE
• Example:
struct person_info
{
int height_cm;
float weight_kg;
};
The variables height_cm and weight_kg are the members (or
fields or elements) of the structure person_info.
Take note that this is just a definition of a structure. It is not a
declaration. That is, it defines only a new data type (called
person_info). No variable is declared so no memory is allocated.
Structures
STRUCTURED VARIABLES
• After the structure definition, the program can now declare
variables of that type.
• The format for declaring structured variables is:
structure_name variable_names;
Example:
person_info person1, person2;
There are now two structured variables called person1 and
person2 of data type person_info.
Structures
ACCESSING struct MEMBERS
• A programmer may reference the members of a
person1 structure variable like ordinary variables of the
same type. However, the variable name and a
dot (period) should precede each member.
height_cm weight_kg
Example:
person1.height_cm = 166;
person1.weight _kg= 72.7;
person2
person2.height_cm = 160;
person2.weight_kg = 54.5;
height_cm weight_kg
• The dot (.) is an operator called the member
access operator.
Structures
ACCESSING struct MEMBERS
• Sample Program
#include <iostream>
using namespace std;
main()
{
struct person_info
{
int height_cm;
float weight_kg;
};
person_info person1, person2;
Structures
ACCESSING struct MEMBERS
cout << "Enter Person 1's height in cm: ";
cin >> person1.height_cm;
cout << "Enter Person 1's weight in kg: ";
cin >> person1.weight_kg;
cout << "\nEnter Person 2's height in cm: ";
cin >> person2.height_cm;
cout << "Enter Person 2's weight in kg: ";
cin >> person2.weight_kg;
cout << "\nPerson 1's height in cm is " << person1.height_cm << ".";
cout << "\nPerson 1's weight in kg is " << person1.weight_kg << ".";
cout << "\n\nPerson 2's height in cm is " << person2.height_cm << ".";
cout << "\nPerson 2's weight in kg is " << person2.weight_kg << ".";
}
Structures
ACCESSING struct MEMBERS
• Another example:
struct book_info
{
char title[50];
char author[50];
int book_id;
};
The variables title, author, and book_id are the members
of the structure book_info. Take note that title and author
are strings.
Structures
ACCESSING struct MEMBERS
To declare variables of struct book_info:
book_info book1, book2;
To enter data:
strcpy (book1.title, "C++ Programming");
strcpy (book1.author, "Mitch M. Andaya");
book1.book_id = 123456;
Or use the get function to enter strings.
Structures
ACCESSING struct MEMBERS
• Sample Program
#include <iostream>
using namespace std;
main()
{
struct book_info
{
char title[50];
char author[50];
int book_id;
};
book_info book1, book2;
Structures
ACCESSING struct MEMBERS
cout << "Enter the title of the first book: ";
cin.get (book1.title, 50);
cin.get();
cout << "Enter the author of the first book: ";
cin.get (book1.author, 50);
cout << "Enter the book ID of the first book: ";
cin >> book1.book_id;
cin.get();
cout << "\nEnter the title of the second book: ";
cin.get (book2.title, 50);
cin.get();
cout << "Enter the second of the second book: ";
cin.get (book2.author, 50);
cout << "Enter the book ID of the second book: ";
cin >> book2.book_id;
Structures
ACCESSING struct MEMBERS
cout << "\nThe title of the first book is " << book1.title << ".";
cout << "\nThe author of the first book is " << book1.author << ".";
cout << "\nThe book ID of the first book is " << book1.book_id << ".";
cout << "\nThe title of the second book is " << book2.title << ".";
cout << "\nThe author of the second book is " << book2.author << ".";
cout << "\nThe book ID of the second book is " << book2.book_id << ".";
Structures
OPTIONS IN DECLARING STRUCTURED VARIABLES
• A programmer may declare the structure variables together with
the structure definition.
struct book_info
struct book_info
{
{
char title[50];
char title[50];
char author[50];
char author[50];
int book_id;
int book_id;
};
}; book1, book2;
book_info book1, book2;
Structures
THE ASSIGNMENT OPERATOR & STRUCTURE VARIABLES
• A program can assign the values of the members or fields
of one structure variable to the members of another
structure variable of the same type.
Example:
struct sample
{
int field1;
char field2;
float field3;
} var1, var2;
Structures
THE ASSIGNMENT OPERATOR & STRUCTURE VARIABLES
var1.field1 = 100; var2.field1 = var1.field1;
var1.field2 = 'A'; var2.field2 = var1.field2;
var1.field3 = 10.5; var2.field3 = var1.field3;
• A shorter way of accomplishing this is:
var2 = var1;
This assigns the values from the members of
structure variable var1 to the members of
structure variable var2.
Structures
ARRAY OF STRUCTURES
• To declare an array of structures, first define a structure, then declare an array
variable of that type.
Example:
struct book_info
{
char title[50];
char author[50];
int book_id;
};
book_info books[50];
To reference the book_id member of the first book:
books[0].book_id = 12345;
Structures
ARRAY OF STRUCTURES
• Sample Program
#include <iostream>
using namespace std;
main()
{
struct book_info {
char title[50];
char author[50];
int book_id;
} books[10];
int index;
Structures
ARRAY OF STRUCTURES
for (index = 0; index <= 9; ++index)
{
cout << "Enter title of book " << index+1 << ": ";
cin.get (books[index].title, 50);
cin.get();
cout << "Enter author of book " << index+1 << ": ";
cin.get (books[index].author, 50);
cout << "Enter book ID of book " << index+1 << ": ";
cin >> books[index].book_id;
cin.get();
cout << "\n\n";
}
Structures
ARRAY OF STRUCTURES
for (index = 0; index <= 9; ++index)
{
cout << "\nThe title of book " << index+1 << " is " << books[index].title
<< ".";
cout << "\nThe author of book " << index+1 << " is " <<
books[index].author << ".";
cout << "\nThe book ID of book " << index+1 << " is " <<
books[index].book_id << ".";
cout << "\n\n";
}
Structures
FUNCTIONS AND STRUCTURE VARIABLES
• Passing a member of a structure variable to a function is similar to
passing an ordinary variable to a function.
Example:
struct sample
{
int field1;
char field2;
float field3;
} var1;
var1.field1 = 100;
var1.field2 = 'A';
var1.field3 = 10.5;
Structures
FUNCTIONS AND STRUCTURE VARIABLES
func1 (var1.field1);
This passes the value of field1 (which is 100) to
function func1.
func2 (var1.field2);
This passes the value of field2 (which is 'A') to
function func2.
func3 (var1.field3);
This passes the value of field3 (which is 10.5) to
function func3.
Structures
FUNCTIONS AND STRUCTURE VARIABLES
• Sample Program
#include <iostream>
using namespace std;
int multiply2 (int x)
{
int answer;
answer = x * 2;
return answer;
}
Structures
FUNCTIONS AND STRUCTURE VARIABLES
char lower (char x)
{
char answer;
answer = tolower(x);
return answer;
}
float divide2 (float x)
{
float answer;
answer = x / 2;
return answer;
}
Structures
FUNCTIONS AND STRUCTURE VARIABLES
main()
{
struct sample
{
int field1;
char field2;
float field3;
} var1;
var1.field1 = 100;
var1.field2 = 'A';
var1.field3 = 10.5;
Structures
FUNCTIONS AND STRUCTURE VARIABLES
var1.field1 = multiply2(var1.field1);
var1.field2 = lower(var1.field2);
var1.field3 = divide2(var1.field3);
cout << "\nField 1 is " << var1.field1;
cout << "\nField 2 is " << var1.field2;
cout << "\nField 3 is " << var1.field3;
}
Structures
FUNCTIONS AND STRUCTURE VARIABLES
• An entire structure variable (all of its members) can also be passed to a function
using the standard call-by-value method.
Example:
struct sample {
int field1;
char field2;
float field3;
} var1;
func (var1);
This passes the values of all the members or fields of var1 to function
func.
• The important thing to remember is that the type of the argument must match
the type of the parameter of the function.
Structures
FUNCTIONS AND STRUCTURE VARIABLES
• Sample Program
#include <iostream>
using namespace std;
struct sample
{
int field1;
char field2;
float field3;
};
Structures
FUNCTIONS AND STRUCTURE VARIABLES
sample process (sample x)
{
x.field1 = x.field1 * 2;
x.field2 = tolower(x.field2);
x.field3 = x.field3 / 2;
return x;
}
Structures
FUNCTIONS AND STRUCTURE VARIABLES
main()
{
struct sample var1;
var1.field1 = 100;
var1.field2 = 'A';
var1.field3 = 10.5;
var1 = process (var1);
cout << "\nField 1 is " << var1.field1;
cout << "\nField 2 is " << var1.field2;
cout << "\nField 3 is " << var1.field3;
}
Structures
POINTERS AND STRUCTURE VARIABLES
• Structures can have pointers in the same manner as ordinary variables in C++.
To declare a structure pointer:
book_info *p; pointer variable p
can now point to
any structure
. variable of type
book_info
To let structure pointer p point to structure variable book1:
p = &book1;
At this point, p is equal to the address of the first memory location allocated to
book1. In other words, p is now pointing to book1.
Structures
POINTERS AND STRUCTURE VARIABLES
• To access the contents of the
fields of book1:
(*p).book_id = 12345;
This statement is equivalent to
book1.book_id = 12345.
Structures
POINTERS AND STRUCTURE VARIABLES
• Sample Program
#include <iostream>
using namespace std;
main()
{
struct book_info
{
char title[50];
char author[50];
int book_id;
} book1;
book_info *p;
Structures
POINTERS AND STRUCTURE VARIABLES
p = &book1;
cout << "Enter title of book 1: ";
cin.get ((*p).title, 50);
cin.get();
cout << "Enter author of book 1: ";
cin.get ((*p).author, 50);
cout << "Enter book ID of book 1: " ;
cin >> (*p).book_id;
cout << "\nThe title of the book is " << (*p).title << ".";
cout << "\nThe author of the book is " << (*p).author << ".";
cout << "\nThe book ID of the book is " << (*p).book_id << ".";
}
Structures
POINTERS AND STRUCTURE VARIABLES
• Sample Program Using Call-by-Reference
#include <iostream>
using namespace std;
struct book_info
{
char title[50];
char author[50];
int book_id;
};
Structures
POINTERS AND STRUCTURE VARIABLES
void getdata (book_info *bk)
{
cout << "Enter title of book 1: ";
cin.get ((*bk).title, 50);
cin.get();
cout << "Enter author of book 1: ";
cin.get ((*bk).author, 50);
cout << "Enter book ID of book 1: " ;
cin >> (*bk).book_id;
}
Structures
POINTERS AND STRUCTURE VARIABLES
void printdata (book_info bk)
{
cout << "\nThe title of the book is " << bk.title << ".";
cout << "\nThe author of the book is " << bk.author << ".";
cout << "\nThe book ID of the book is " << bk.book_id << ".";
}
main()
{
book_info book1;
getdata (&book1);
printdata (book1);
}
Structures
THE ARROW (->) OPERATOR
• An alternative in referencing the elements of a structure using
pointers is by using the arrow operator -> (minus sign followed by
the greater than symbol).
• The arrow operator can take the place of the dot operator when
accessing a structure element.
Example:
p -> book_id = 12345;
is the same as:
(*p).book_id = 12345;
Structures
THE ARROW (->) OPERATOR
• Sample Program
#include <iostream>
using namespace std;
main()
{
struct book_info
{
char title[50];
char author[50];
int book_id;
} book1;
book_info *p;
Structures
THE ARROW (->) OPERATOR
p = &book1;
cout << "Enter title of book 1: ";
cin.get (p->title, 50);
cin.get();
cout << "Enter author of book 1: ";
cin.get (p->author, 50);
cout << "Enter book ID of book 1: " ;
cin >> p->book_id;
cout << "\nThe title of the book is " << p->title << ".";
cout << "\nThe author of the book is " << p->author << ".";
cout << "\nThe book ID of the book is " << p->book_id << ".";
}
Structures
STRUCTURES WITH POINTER FIELDS
• Since the fields of a structured variable are just like ordinary
variables, these fields can also be pointer variables.
Example:
struct sample
{
int number;
int *ptr;
} var1;
In this example, the second field of structured variable var1 is an
integer pointer variable.
Structures
STRUCTURES WITH POINTER FIELDS
• To make the pointer ptr of the structure
variable var1 point to an integer variable x:
var1.ptr = &x;
To change the contents of x to 5:
*var1.ptr = 5
Structures
struct WITHIN struct
• There are situations for which it is beneficial to organize data in a
struct by using another struct (or structs).
• Consider the following structure definition:
struct person_info
{
char first_name[25]; int age;
char middle_name[25]; int height_cm;
char last_name [25] float weight_kg;
char no_street[25]; char spouse_fname[25];
char barangay[25]; char spouse_mname[25];
char city [25] char spouse_lname [25]
};
Structures
struct WITHIN struct
• There may be many information packed into one struct. Some
members 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.
• Consider now this approach:
struct name_type struct address_type
{ {
char first[25]; char no_street[25];
char middle[25]; char barangay[25];
char last [25] char city [25]
}; };
Structures
struct WITHIN struct
• A new structure containing a person’s information may
now be defined as:
struct person_info
{
name_type name;
address_type address;
int age;
int height_cm;
float weight_kg;
name_type spouse_name;
};
Structures
struct WITHIN struct
• To declare a variable person1 of type person_info:
person_info person1;
• To prompt the user to enter the name of person1:
cout << "Enter first name of person 1: ";
cin.get (person.name.first, 25);
cout << "Enter middle name of person 1: ";
cin.get (person.name.middle, 25);
cout << "Enter last name of person 1: ";
cin.get (person.name.last, 25);
Structures
MACHINE PROBLEMS
1. Write a program that reads students' names followed by
their test scores and grades. The program should output
each student’s name followed by the test scores and the
relevant grade. It should also find and print the highest
test score and the name of the students having the highest
test score.
Student data should be stored in a struct variable of type
student_type, which has three components: name which is
a string with a maximum of 50 characters, score of type int
(score is between 0 and 100), and grade of type float.
Suppose that the class has 5 students. Use an array of 5
components of type student_type.
Structures
MACHINE PROBLEMS
The program must contain at least the following functions:
a. A function to read the students' data into the array.
b. A function to print all the data of the array.
c. A function to find and return the highest test score.
d. A function to print the names of the students
having the highest test score.
Moreover, other than declaring the variables, main()
should mostly be a collection of function calls.
Sturctures
MACHINE PROBLEMS
2. Repeat Machine Problem 1 but this time, use pointers instead of array indexing.
Also, the program should assign the grade based on the score entered by the
user using the following table:
Score Grade
0–69 5.00
70–73 3.00
74–77 2.75
78–80 2.50
81–83 2.25
84–87 2.00
88–90 1.75
91–93 1.50
94–97 1.25
98–100 1.00
Structures
MACHINE PROBLEMS
3. Write a program to help a local restaurant automate its breakfast billing system.
The program should do the following:
a. Show the customer the different breakfast items offered by the
restaurant.
b. Allow the customer to select more than one item from the menu.
c. Calculate and print the bill.
Assume that the restaurant offers the following breakfast items (the price
of each item is shown to the right of the item):
Continental Breakfast 349.99 pesos
Filipino Breakfast 285.00 pesos
Fruit Platter 172.50 pesos
French Toast 95.25 pesos
Pancakes 65.00 pesos
Use an array, menu, of the struct menu_type, with two fields (food which is a
string with a maximum of 20 characters and price which is of type float).
Structures
MACHINE PROBLEMS
After entering the data in the array, the program will prompt the user to make
choices from the menu.
The output should look like:
Welcome to Mitch Andaya Restaurant
1 Continental Breakfast 349.99 pesos
2 Filipino Breakfast 285.00 pesos
3 Fruit Platter 172.50 pesos
4 French Toast 95.25 pesos
5 Pancakes 65.00 pesos
6 Finish
Enter the number of your choice:
Structures
MACHINE PROBLEMS
The program should not accept an invalid choice (any choice that is not 1, 2, 3,
4, 5, or 6). The user should be able to choose several items from the menu
(even the same item). For example:
Enter the number of your choice: 2
You have chosen Filipino Breakfast.
Please choose another item.
Enter the number of your choice: 3
You have chosen Fruit Platter.
Please choose another item.
Enter the number of your choice: 2
You have chosen Filipino Breakfast.
Please choose another item.
Enter the number of your choice:
Structures
MACHINE PROBLEMS
Once the user chooses 6 (Finish), the program should then
calculate and print the bill. For example:
Enter the number of your choice: 6
Thank you for your choices. Your bill is:
2 orders of Continental Breakfast 699.98 pesos
3 orders of Filipino Breakfast 855.00 pesos
1 orders of Fruit Platter 172.50 pesos
TOTAL AMOUNT: 1727.48 pesos
Make sure all amounts are printed using 2 decimal places.
Structures