Fundamentals of Structured
Programming
Lecture 3 - Structures
Agenda
1. Structures
- Why?
- Declaration
- Initialization
- Elements (fields/member variables) Referencing
- Copying
2. Arrays of Structures
3. Nested Structures
4. Examples
-2-
Opening Question
To store 0,1,2,3,4,5,6,7,8,9, you will use array of int.
To store 'a,'v','r','w','r','q' , you will use array of char.
But, what if you want to store 1,2,'a’,4,”fffgb”,'x’ ?
what will you use?
-3-
What is a Structure?
Structure is collection of variables of different
types.
Structure is called an “aggregate” data type.
Enables you to manage several variables under
one name.
every variable is called a structure member and has its
own independent memory that means we can access any
member anytime.
-4-
Why Structures?
Structures adds organization and structure to
your program.
For example:
➢ If you want to track the information of a number of
students, like their id, GPA, letterGrade, etc. You can
do it very easily with the help of structure.
1D arrays
Information about a student
Structure
-5-
What is a Structure? Why? – (cont.)
Information about a student
1D arrays
int ID[4]; float GPA[4]; char letterGrade[4]
St1 2008170001 St1 3.3 St1 B
St2 2008170002 St2 2.0 St2 C
St3 2008170003 St3 4.0 St3 A
St4 2008170004 St4 3.7 St4 A
What is a Structure? Why? – (cont.)
Information about a student
Structure Stu1
ID 2008170001
GPA 3.3
Grade B
Stu2
ID 2008170002
GPA 2.0
Grade C
.
.
.
Structure Syntax
struct name_of_structure
{ Defined
above
member-list
main
};
we may use string or an array of characters -8-
How to represent a vehicle?
vehicle
-10-
after definition and
before semi colon
declared as global
variables
-11-
Memory Allocation
memory address is Hex number, here it is int for simplicity
struct employee
{
int id;
char Name[10];
float salary;
};
employee emp;
Adjacent memory locations are used to store structure
members.
-12-
inside main function
Order is important!
-13-
Initializing structures (2nd way)
Set values of member variables
individually using DOT operator:
Student s;
s.name=“Salma”;
s.ID = 2018170142;
Read values from the user.
cin>>s.name;
-14-
-15-
Structure Declaration
Name of new struct "type"
Name and types of members
• Does not allocate
memory. It’s just an
indication of what our
structure will look like.
Structure Variable Declaration (1)
Structure
Stu1 variable
ID
Member Name ……..……..
variables Grades
17
Structure Variable Declaration (2)
Stu1
ID 0
Name
Grades 0 0 0 0 0
Stu2
ID 0
Name
Grades 0 0 0 0 0
Auto initialized to zeros
Stu3
ID
Name
Grades
Stu4
ID
Name
Grades
Structure Variable Initialization
Stu1
ID 0
Name
Grades 0 0 0 0 0
Stu2
ID 0
Name
Grades 0 0 0 0 0
Stu3
ID 2008170003
Name S A L M A H A M …
Grades 59 89 90 100 50
Stu4
ID 2008170004
Name
Grades 0 0 0 0 0
Structure Variable Members
Stu3
ID 2008170003
Name S A L M A H A M …
Grades 59 89 90 100 50
20
Structure Variable Members
Stu3
ID 2008170003
Name S A L M A H A M …
Grades 59 89 90 100 50
• Your IDE will list all the
member variables of this
structure type.
21
Structure Variable Members
Stu3
ID 2008170003
Name S A L M A H A M …
Grades 59 89 90 100 50
NOT AN ACTUAL PLACE
IN MEMORY
22
Structure Variable Members
Stu3
ID 2008170003
Name S A L M A H A M …
Grades 59 89 90 100 50
array name stores the memory
address of its first element
23
Structure Variable Members
Stu3
ID 2008170003
Name S A L M A H A M …
Grades 59 89 90 100 50
What’s the difference
between line 24 and
lines 25-26 ?
24
Structure Variable Members
Stu3
ID 2008170003
Name S A L M A H A M …
Grades 59 89 90 100 50
25
More than one struct Type
26
Copying Structure Variables
What about
copying
structs
2
27
7
Copying Structure Variables
emp1 = std1;
Copying for variable of
the same structure type
only. Different structure
types cannot be copied
even if they had the same
member variables!
std2 = std1;
-28-
-29-
-30-
int main ( )
{
-31-
-32-
-33-
34
Array of Structures
Array holds elements of the same type. Thus, an array can be of structure type.
3535
*
Structure?
Array name not
structure name
Struct Student
{
char id[6];
char name[50];
char gender;
int age;
};
Student stud[10]; Array of Structures
3636
Structure?
3737
Arrays of Structures
Example 1
Program accepts Input
the grades of 2
students in three
subjects, and
displays the their
average scores Output
along with a
pass/fail status.
Click Here for Complete Code
Example 1 Solution
#include <iostream>
using namespace std;
#define nSubjects 3
struct stud
{
int id;
float grades[nSubjects];
float avg;
char status;
};
-39-
*
void main()
{
const int nStuds = 2;
stud students[nStuds];
int total;
for (int i=0; i < nStuds; i++)
{
total = 0;
cout<< "Enter id: ";
cin>> students[i].id;
cout<< "Enter "<< nSubjects <<" grades:\n";
for(int j=0; j < nSubjects; j++)
{
cin >> students[i].grades[j]; How will we refer to
each grade?
total += students[i].grades[j];
}
40
for (int i=0; i < nStuds; i++)
{
total = 0;
for(int j=0; j < nSubjects; j++)
{
cin >> students[i].grades[j];
total += students[i].grades[j];
}
id grades[0] grades[1] grades[2] avg Status
students [0]
id grades[0] grades[1] grades[2] avg Status
students [1]
students[i].avg= (float) total/nSubjects;
if(students[i].avg >= 50)
students[i].status= 'p';
else
students[i].status= 'f';
} // outer for
//output
cout<< "ID\tAvg\t\tStatus\n";
for (int i=0; i < nStuds; i++)
cout<< students[i].id <<"\t"
<< students[i].avg
<<"\t\t"<< students[i].status
<< endl;
}// main
42
Nested Structures
Structure of Structures
nested structure must be
declared before the outer
structure so that the
compiler could translate it
Emp.
Name
Add.
HouseNo
City
Employee Emp;
-44-
-45-
Output
-46-
Nested Structures
Structure of Structures
• Update the design of Example 1 to include
the birthdate of each student.
• Read in three subjects, and display the
average score of each student along with a
pass/fail status.
-47-
#include <iostream>
using namespace std;
#define nSubjects 3
struct date
{
int day;
int month;
int year;
};
struct stud
{
int id;
date DOB;
float grades[nSubjects];
float avg;
char status;
} ;
48
void main()
{
const int nStuds = 2;
stud students[nStuds];
int total;
for(int i=0; i < nStuds; i++)
{
total = 0;
cout<< "Enter id: ";
cin>> students[i].id;
cout<< "Enter Date of Birth:\n day: ";
cin>> students[i].DOB.day;
cout<< "month: ";
cin>> students[i].DOB.month;
cout<< "year: ";
cin>> students[i].DOB.year;
49
cout<< "Enter "<< nSubjects <<" grades:\n";
for(int j=0; j < nSubjects; j++)
{
cin >> students[i].grades[j];
total += students[i].grades[j];
}
students[i].avg= (float) total/nSubjects;
if(students[i].avg >= 50)
students[i].status= 'p';
else
students[i].status= 'f’;
}//outer for
50
//output
cout<< "ID\tDOB\t\tAvg\t\tStatus\n";
for(int i=0; i < nStuds; i++)
cout<< students[i].id<<"\t"
<< students[i].DOB.day<<"/"
<< students[i].DOB.month<<"/"
<< students[i].DOB.year<<"\t"
<< students[i].avg<<"\t\t"
<< students[i].status<< endl;
51
Problem (Structs with functions)
Write a C++ program for a car maintenance agency that
keeps information about 4 cars including the license
number, type (H for Hatchback or S for Sedan) and date
for next maintenance.
A function displays all information about the cars that
need maintenance before 1/1/2020 of a specific type
entered by the user.
52
#include <iostream>
using namespace std;
struct date
{ int day, month, year;};
struct vehicle
{
int LisenceNum;
char type;
date mDate;
}; Global Variable
vehicle cars[4];
void DisplayCars(char type)
{
for (int i = 0; i < 4; i++)
if ((cars[i].mDate.year < 2020) && (type == cars[i].type))
cout << cars[i].LisenceNum << ", "
<< cars[i].mDate.day << '/'
<< cars[i].mDate.month <<'/'<<
cars[i].mDate.year << endl;
} 53 53
void main ()
{ char type;
for (int i = 0; i < 4; i++)
{
cout << "Enter Car Lisence Number: ";
cin >> cars[i].LisenceNum;
cout << "Enter type (S/H): ";
cin >> cars[i].type;
cout << "Enter date: ";
cin >> cars[i].mDate.day >>
cars[i].mDate.month >>
cars[i].mDate.year;
}
cout <<"Enter your designated type: ";
cin >> type;
DisplayCars(type);
54 54
}
Passing Structs to Functions
Example :
• Function to input (fill) structure
fields.
• Function to output structure fields.
55
Passing Structs to Functions
#include <iostream>
using namespace std;
const int SCORES = 3;
struct Stud
{
int ID;
double scores[SCORES];
bool pass;
};
// Function declarations
Stud input();
void display(Stud);
56
Stud input()
{
Stud s;
cout<<"Enter student ID: ";
cin>>s.ID;
cout<<"Enter student scores: ";
for(int i =0; i < SCORES; i++)
cin>>s.scores[i];
return s;
} // end input
void display(Stud s) // by value
{
cout<<"ID\tScores\t\tStatus\n";
cout<< s.ID <<"\t";
for(int i =0; i < SCORES; i++)
cout<< s.scores[i] <<" ";
if (s.pass)
cout<<"\tPassed\n";
else
cout<<"\tFailed\n";
s.ID = 3; // should NOT affect the variable s1 in main
} // end display
57
int main()
{
// variables
Stud s1 = {0};
double sum = 0;
s1 = input();
for(int i=0; i < SCORES; i++)
sum += s1.scores[i];
float avg = sum/(float)SCORES;
if(avg >= 50)
s1.pass = true;
else
s1.pass = false;
// output
display(s1);
cout << "In main: " << endl;
cout << s1.ID <<endl; // not affected by changes to var s1
// in function display
return 0;
} // end main
58
Home Assignment 3
In our factory, we had multiple products. The details of each product were
serialNum, quantity, totalSales). Instead of representing products in three
arrays, represent them in one array of structures where each structure
consists of : serial number, quantity, total_sales and price.
1. Update all the functions in home assignment 2 to match the new product
representation.
2. Add function that would display all the products.
3. Add function to apply 50% discount on the price of products that have less
than 6 items left.
4. Add a menu so that the user chooses which functionality they want to use.
The program should keep asking the user if they want to use another
function and only stops when the user enters ‘n’.
Note that the array will be global.
-59-
Please enter a number:
Sample Run Press 1 to get products that have less
quantity than a certain value
Please enter the four products: Press 2 to Get Product with the highest
Enter values of product #1 sales
Serial num : 101 Press 3 to Apply 50% discount for
quantity: 5 products that have quantity less than 6
sales : 10 Press 4 to Display all the products
price : 20 1
Enter values of product #2 Please enter the quantity: 11
Serial num : 102
quantity: 10 Product 101
sales : 6 Product 102
price : 10
Enter values of product #3 Product 104
Serial num : 103 Do you want to Apply Another function,
quantity: 11 Press 'Y' or 'y' for yes, any other key
sales : 20 to stop :y
price : 30
Please enter a number:
Enter values of product #4
Press 1 to get products that have less
Serial num : 104
quantity than a certain value
quantity: 9
Press 2 to Get Product with the highest
sales : 12
sales
price : 40
Press 3 to Apply 50% discount for
products that have quantity less than 6
Press 4 to Display all the products
2
Product 3
60
product #1
Do you want to Apply Another function,
Serial num : 101
Press 'Y' or 'y' for yes, any other key
quantity: 5
to stop :y sales : 10
------------------------------------ price : 10
Please enter a number: product #2
Press 1 to get products that have less
Serial num : 102
quantity than a certain value quantity: 10
Press 2 to Get Product with the highest
sales : 6
sales price : 10
Press 3 to Apply 50% discount for
product #3
products that have quantity less than 6 Serial num : 103
Press 4 to Display all the products quantity: 11
3 sales : 20
Discount Applied. price : 30
Do you want to Apply Another function,
product #4
Press 'Y' or 'y' for yes, any other key
Serial num : 104
to stop :y
quantity: 9
--------------------------- sales : 12
Please enter a number: price : 40
Press 1 to get products that have less
quantity than a certain value Do you want to Apply Another
Press 2 to Get Product with the highest function, Press 'Y' or 'y' for yes,
sales any other key to stop :n
Press 3 to Apply 50% discount for
products that have quantity less than 6
Press 4 to Display all the products
4
61
To Do list
• Sheet 3
• Home Assignment 3
• Choose team members
Project
Announcement
62