Professional Documents
Culture Documents
CS1010E Lecture 6
Structures
Analysis:
How do we represent a point in the
Cartesian plane? As two separate values,
or as one aggregate value?
Calculate the distance between two points
(x1 , y1 ) and (x2 , y2 ) using
p
distance = (x2 x1 )2 + (y2 y1 )2
Henry Chia
hchia@comp.nus.edu.sg
Lecture Outline
Structures.
Structure definition.
Declaration with structures.
Assigning structures.
Accessing members of a structure.
x1
1.0
y1
1.0
x2
2.0
y2
2.0
computeDist
x1
1.0
y1
1.0
x2
2.0
y2
2.0
distance
1.0,1.0,2.0,2.0
return 1.414..;
1.414..
distance = computeDist(x1,y1,x2,y2);
CS1010E Lecture 6 p.2/24
Structures
#include library_headers
#define CONSTANTS
struct struct_definitions
int main(void)
{
declarations
statements
}
function_definitions
Structure Definition
Structure Definition
Defining a structure is to define a new type.
struct struct_identifier
{
declarations
}; // Note the semi-colon
struct Point
{
double x, y;
};
struct Fraction
{
int num;
int den;
};
struct BankAccount
{
int accountNum;
double balance;
};
Point
Point
Point
Point
pt1={1.2,3.4};
unit={1};
origin={0};
pt2;
//
//
//
//
(1.2,3.4)
(1.0,0.0)
(0.0,0.0)
(?,?)
pt1
1.2
3.4
1.2
3.4
pt2
1.2
3.4
pt2 = pt1;
pt1
pt2
Member Operator
Member Operator
Member Operator
pt1.x = 1.2;
pt1.y = 3.4;
Returning a Structure
computeDist
pt1
1.0 1.0
pt1
1.0 1.0
pt1
1.0 1.0
pt2
2.0 2.0
pt2
2.0 2.0
pt2
2.0 2.0
{1.0,1.0},{2.0,2.0}
{1.0,1.0},{2.0,2.0}
distance
return 1.414..;
midPoint
pt1
1.0 1.0
pt2
2.0 2.0
*
1.5 1.5
{1.5,1.5}
return midpt;
midpt = midPoint(pt1,pt2);
CS1010E Lecture 6 p.17/24
Returning a Structure
/ 2;
/ 2;
midpt
midpt
1.414..
distance = computeDist(pt1,pt2);
Point pt1,
Point pt2)
x 1 + x 2 y1 + y2
,
)
2
2
struct Point
{
double x, y;
};
noOverlap = r1.min.x
r2.min.x
r1.min.y
r2.min.y
struct Rect
{
struct Point min, max;
};
int overlap(struct Rect r1, struct Rect r2);
struct Rect getRectangle();
struct Point getPoint();
>
>
>
>
r2.max.x ||
r1.max.x ||
r2.max.y ||
r1.max.y;
return !noOverlap;
}
int main(void)
{
struct Rect r1, r2;
r1 = getRectangle();
r2 = getRectangle();
if (overlap(r1,r2))
printf("Rectangles overlap.\n");
else
printf("Rectangles do not overlap.\n");
return 0;
}
CS1010E Lecture 6 p.21/24
Lecture Summary
Definition of structures before usage
(declarations, functions, etc.)
r.min = getPoint();
r.max = getPoint();
return r;
}