Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

1

STRUCTURES
Chapter 7
Outline
2

 Introduction
 Structure Definitions and Declarations
 Initializing Structures
 Operations on Structures Members
 Structures as Functions Parameters
 Array of Structures
What is Structures?
3

 Collection of related data items called components (or


members) that are NOT necessarily of the same data
type.
 Commonly used to define records to be stored in files.
 Usually the collections of related data item are
characteristics in an object
 For example:
Object Characteristic
Book price, number_of_pages, year published
Car price, year, model, colour
Student name, matric_no, semester
Structure Definition
4

 Syntax:
struct StructureName
{
structure member declaration list
};

 Example:
struct book
{
float fPrice;
int iNumPages;
int iYear;
};
Structure Definition
5

 struct information
 A struct cannot contain an instance of itself
 Can contain a member that is a pointer to the same
structure type
 A structure definition does not reserve space in memory
• Instead creates a new data type used to define structure
variables
Structure Declaration
6

 After defining a structure type, we may declare


variables that are of that type. A structure variable
declaration requires these elements :
 keyword struct
 structure type name
 a list of variables names separated by commas
 concluding semicolon
 Example:
 struct book sBook1;
 struct book sMyBook,sHisBook,sHerBook;
Structure Declaration
(Example)
7

#include <stdio.h> #include <stdio.h>


struct book struct book
{ {
float fPrice; float fPrice;
int iNumPages; int iNumPages;
int iYear;
int iYear;
} sBook1;
}; or
int main( ) int main( )
{
{
struct book sBook1; ……
…… }
}

struct book sBook1;


Initializing Structures
8

struct book sBook1 = {25.50, 690, 2005};

OR

sBook1.fPrice = 25.50;
sBook1.iNumPages = 690;
sBook1.iYear = 2005;
dot operator
Operations on Structures Members
9

Operation Normal variable Structure member


Read from user scanf(“%f”, &fPrice); scanf(“%f”, &sBook1.fPrice);
Assign value fPrice = 25.50; sBook1.fPrice = 25.50;
Print as output printf(“%f\n”, fPrice); printf(“%f\n”, sBook1.fPrice);
Copy to a variable fNewPrice = fPrice; fNewPrice = sBook1.fPrice;
Pass value to a function if(fnFun1(fPrice) > 5) if(fnFun1(sBook1.fPrice) > 5)
Multiple Structures Variables
10

 Example:
struct book sMyBook, sHisBook, sHerBook;

• fPrice • fPrice • fPrice

• iNumPages • iNumPages • iNumPages

• iYear • iYear • iYear

sMyBook sHisBook sHerBook


Multiple Structures Variables
11

 Example:
struct book sMyBook, sHisBook, sHerBook;
sMyBook. fPrice = 25.50;
sHerBook.fPrice = 10.50;
if(sMyBook.fPrice > sHerBook.fPrice)
printf(“My book is more expensive than hers\n”);
else
printf(“My book is cheaper than hers\n”);
Multiple Structures Variables
(Example)
12

#include <stdio.h> printf("My book :\n");


struct book printf("%.2f\t%d\t%d\n", sMyBook.fPrice,
{ sMyBook.iNumPages, sMyBook.iYear);
float fPrice; printf("Her book :\n");
printf("%.2f\t%d\t%d\n", sHerBook.fPrice,
int iNumPages;
sHerBook.iNumPages, sHerBook.iYear);
int iYear;
}; if(sMyBook.iYear > sHerBook.iYear)
int main() printf("My book is the latest publication\n");
{ struct book sMyBook = {25.50,690,2005}; else
struct book sHerBook; printf("Her book is the latest publication\n");
return 0;
}
printf("Enter book price : "); Output:
scanf("%f", &sHerBook.fPrice); Enter book price : 99.99
Enter number of pages : 1000
printf("Enter number of pages : ");
Enter year published : 2020
scanf("%d", &sHerBook.iNumPages); My book :
printf("Enter year published : "); 25.50 690 2005
scanf("%d", &sHerBook.iYear); Her book :
99.99 1000 2020
Her book is the latest publication
Structures as Function Parameters
13

 Like variables of any other data type, structure


variables can be used as formal and actual
function parameters.
 In passing structure variables by value to a
function, the operating systems makes a copy of
the entire structure in the data area of the called
function.
Structures as Function Parameters
14

……
float fnComputePrice(struct book sBkC); //function prototype

int main( )
{ struct book sBookC;
……………
fNewPrice = fnComputePrice(sBookC); //function call
……
}
float fnComputePrice(struct book sBkC) //function definition

{ …….
sBkC.fPrice=sBkC.fPrice + fTax;
……
return(fBkC.fPrice);
}
Structures as Function Parameters
15

 A nonvoid function of a structure type can return a


structure of that structure type under the function’s
name if we use a return statement in the function
struct book fnRead (); //function prototype
int main( )
{ ……….
struct book sB;
sB = fnRead( ); //function call
……….
}
struct book fnRead( ) //function definition
{ struct book sBk;
printf(“Enter price:”);
scanf(“%f”, &sBk.fPrice);

…..
return(sBk);
}
Structures as Function Parameters
16

 If all members of a structure variable are not needed for a


function to perform its task, we can pass only the required
members
 However, we must specify structure members using the
component selection operator
int fnModifyYear(int iA, int iB, int iYear); //function prototype
……..
int main( )
{ struct book sBkC;
…………….
iAvgYear=fnModifyYear(iAa, iBb, sBkC.iYear); //function call
…….
}
Structures as Function Parameters
17

 It is possible to pass structure variables using pointers


int main()
{ struct book sB;
………
fnRead(&sB); //function call
}
void fnRead(struct book *sBk)
{
printf(“Enter price:”);
scanf(“%f”, &sBk->fPrice);
printf(“Enter numpages:”);
scanf(“%d”, &sBk->iNumPages);
…….
}
Structures as Function Parameters
(Example)
18
#include <stdio.h> struct book fnRead()
struct book { struct book sHerBook;
{
float fPrice; printf("Enter book price : ");
scanf("%f", &sHerBook.fPrice);
int iNumPages; printf("Enter number of pages : ");
int iYear; scanf("%d", &sHerBook.iNumPages);
}; printf("Enter year published : ");
struct book fnRead(); scanf("%d", &sHerBook.iYear);
void fnPrint(struct book, struct book); return(sHerBook);
void fnCompare(int, int); }
int main() void fnPrint(struct book sMyBook, struct book sHerBook)
{ {
struct book sMyBook = {25.50,690,2005}; printf("My book :\n");
printf("%.2f\t%d\t%d\n", sMyBook.fPrice,
struct book sSheBook; sMyBook.iNumPages, sMyBook.iYear);
sSheBook=fnRead(); printf("Her book :\n");
fnPrint(sMyBook , sSheBook); printf("%.2f\t%d\t%d\n", sHerBook.fPrice,
fnCompare(sMyBook.iYear, sSheBook.iYear); sHerBook.iNumPages, sHerBook.iYear);
return 0; }
Output: void fnCompare(int iMyYear, int iSheYear)
}
Enter book price : 88.30 {
Enter number of pages : 200 if(iMyYear > iSheYear)
Enter year published : 1995 printf("My book is the latest publication\n");
My book : else
25.50 690 2005 printf("Her book is the latest publication\n");
Her book : }
88.30 200 1995
My book is the latest publication
An Array of Structures
19

 Suppose a company has 50 full-time employees.


struct employeeType
{
char acFirstName[20];
char acLastName[20];
int iPersonID;
char acDeptID[10];
double dYearlySalary;
double dMonthlySalary;
double dYearToDatePaid;
double dMonthlyBonus;
};
struct employeeType asEmployees[50];
How it looks like?
20

[0] Array of structs asEmployees


[1]
[2]
.
. asEmployees[2]
. acFirstName
[25]
acLastName
[26] iPersonID
.
acDeptID
. dYearlySalary
.
dMonthlySalary
[48]
dYearToDatePaid
[49]
dMonthlyBonus
How to access?
21

int iCounter;

for(iCounter = 0; iCounter < 50; iCounter++)


{
scanf(“%s %s %d %s %lf”, &asEmployees[iCounter].acFirstName,
&asEmployees[iCounter].acLastName, &asEmployees[iCounter].iPersonID,
&asEmployees[iCounter].acDeptID, &asEmployees[iCounter].dYearlySalary);
asEmployees[iCounter].dMonthlySalary = asEmployees[iCounter].dYearlySalary/12;
asEmployees[iCounter].dYearToDatePaid = 0.0;
asEmployees[iCounter].dMonthlyBonus = 0.0;
}
How to access?
22

 Suppose that for a given month the monthly bonuses are


already stored in each employee’s record, and we have to
calculate the monthly paycheck and update the
yearToDatePaid amount. The following loop computes and
prints the employee’s paycheck for the month:
double dPayCheck; //variable to calculate the paycheck
for(iCounter = 0; iCounter < 50; iCounter++)
{
printf(“%s %s”, asEmployees[iCounter].acFirstName, asEmployees[iCounter].acLastName);
dPayCheck = asEmployees[iCounter].dMonthlySalary + asEmployees[iCounter].dMonthlyBonus;
asEmployees[iCounter].dYearToDatePaid = asEmployees[iCounter].dYearToDatePaid + dPayCheck;
}
Arrays in Structures (Example)
23

const arraySize = 5;
struct listType
{
int aiListElem[arraySize]; //array containing the list
int iListLength; //length of the list
}; aiListElem

struct listType sList;

iListLength
Structure Within a Structure
24

struct nameType struct contactType


{ {
string acFirst; string acPhone;
string acMiddle; string acCellphone;
string acLast; string acFax;
}; string acPager;
struct addressType string acEmail;
{ };
string acAddress1; struct employeeType
string acAddress2; {
string acCity; struct nameType sName;
string acState; string acEmplID;
string acZip; struct addressType sAddress;
}; struct dateType sHiredate;
struct dateType struct dateType sQuitdate;
{ struct contactType sContact;
string acMonth; string acDeptID;
string acDay; double dSalary;
string acYear; };
};
Structure Within a Structure
(How to access?)
25

//variable declaration
struct employeeType sNewEmployee;
//declare 100 employees' records
struct employeeType asEmployees[100];
sNewEmployee.dSalary = 45678.00;
sNewEmployee.sName.acFirst = "Mary";
sNewEmployee.sName.acMiddle = "Beth";
sNewEmployee.sName.acLast = "Simmons";
//reads and stores a string into sNewEmployee.sName.acFirst
scanf(“%s”, &sNewEmployee.sName.acFirst);
//updates the salary of newEmployee
sNewEmployee.dSalary = sNewEmployee.dSalary * 1.05;
PGT 106: Computer Programming 26

Q&A Dr. Husna Jamal Abdul Nasir

You might also like