<<

Why Data Structures?

Lecture P4: Structs and Data Types Goal: deal with large amounts of data. addr value ■ Organize data so that it is easy to manipulate. 0 0 ■ Time and space efficient. 1 1 2 1 Basic computer memory abstraction. 3 1 ■ Indexed sequence of . 4 0 struct student { ■ Address = index. char name[20]; 5 1 int age; Need higher level abstractions to bridge gap. 6 0 double salary; ■ 7 0 } Hal, Bill; Array.

■ STRUCT. 8 1

■ Linked list. 9 0

■ Binary tree. 10 1 ■ Database...... ■ . . . 256GB 1

2

Structs C Representation of C Students

student.c Fundamental . #include ■ HETEROGENEOUS collection of values (possibly different type). – Database records, complex numbers, linked list nodes, etc. struct struct student { declaration ■ Store values in FIELDS. char name[16]; int grade; ■ Associate NAME with each field. }; name grade ■ Use struct name and field name to access value.

Built-in to C. int main(void) { can initialize struct student t; ■ To access rate field of structure x use x.rate struct fields in struct student x = {"Bill Gates", 60}; ■ Basis for building "user-defined types" in C. declaration struct student y = {"Steve Jobs", 70};

access structs if (x.grade > y.grade) name of field id rate first last as ordinary t = x; else %s for string struct variables value 166316754 11.50 "Bill" "Gates" t = y; printf("Better student: %s\n", t.name); return 0; field field field field } 3 4 Typedef A : Points

User definition of type name. Define structures for points in the plane, and operations on them.

■ Put type descriptions in one place - makes code more portable. point data type ■ Avoid typing struct - makes code more readable. #include typedef struct { double x; typedef int Grade; double y; typedef char Name[16]; a } Point; 2 + 2 struct student { dx dy double distance(Point a, Point b) { Name name; dy double dx = a.x - b.x; Grade grade; double dy = a.y - b.y; }; b return sqrt(dx*dx + dy*dy); dx } typedef struct student Student; Point randomPoint(double s) { Point p; random point with x . . . p.x = randomDouble(s); and y coordinates p.y = randomDouble(s); between 0.0 and s Student x = {"Bill Gates", 60}; return p; }

5 6

Another Data Type: Circles Using Data Types: Estimating Pi

Define struct for circles, and operations on them. Estimate pi. pi.c circle data structure ■ Generate N random points #define N 100000 #include in 2 x 2 square. ■ Determine fraction that lie int main(void) { typedef struct { in unit circle. int i, cnt = 0; Point center; ■ On average pi / 4 fraction Point p = {1.0, 1.0}; double radius; center should lie in circle. Circle c; } Circle; c.center = p; c.radius = 1.0; ■ Use 4 * fraction as p estimate of pi. int inCircle(Point p, Circle c) { for (i = 0; i < N; i++) { return distance(p, c.center) <= c.radius; p = randomPoint(2.0); } if (inCircle(p, c)) (2, 2) cnt++; double area(Circle c) { } return 3.14 * c.radius * c.radius; (1, 1) } printf("pi = %f\n", 4.0*cnt/N); return 0; int intersectCircles(Circle c, Circle d) { 1 } return distance(c.center, d.center) <= c.radius + d.radius; (0, 0) } 7 9 Standard Data Type Implementation Intuition

Data type:

of values and collection of operations on those values.

Example (built-in): int, double, char. multiply Example (user defined): complex numbers.

■ Set of values: 4 + 2i, 1.3 - 6.7i, etc. add Complex show ■ Operations: add, multiply, show, etc. Client Implementation Separate implementation from specification. - volume - cathode ray tube . . . ■ INTERFACE: specifies allowed operations. - change channel - electron gun - adjust picture - Sony Wega 36XBR250 ■ IMPLEMENTATION: provides code for operations. - decode NTSC, PAL - 241 pounds, $2,500 ■ CLIENT: uses data type as black box. signals

10 11

Complex Number Data Type Complex Number Data Type: Interface

Create data structure to represent complex numbers. Interface lists allowable operations on complex data type.

■ See Sedgewick 4.8. ■ Name interface with .h extension.

■ Store in rectangular form: real and imaginary parts. COMPLEX.h

typedef struct { typedef struct { double re; store in double re; multiply double im; rectangular form double im; } Complex; } Complex; add Complex show can't reuse Complex COMPLEXadd (Complex, Complex); +, * symbols Complex COMPLEXmult (Complex, Complex); Complex COMPLEXpow (Complex, Complex); . . . Complex COMPLEXconj (Complex); function double COMPLEXabs (Complex); prototypes double COMPLEXreal (Complex); double COMPLEXimag (Complex); Complex COMPLEXinit (double, double); void COMPLEXshow (Complex);

13 14 Complex Number Data Type: Client Complex Number Data Type: Another Client

Client program uses interface operations to calculate something: Redo Mandelbrot with equivalent complex number update: client.c r Ä x, s Ä y c Ä z = x + iy while (r2 + s2 ≤ 4) while (|c| ≤ 2) #include r' Ä r2 -s2 + x c Ä c2 + z #include "COMPLEX.h" client can use interface s' Ä 2rs + y int main(void) { clientmand.c Complex a, b, c; #define MAXIT 255 a = COMPLEXinit( 5.0, 6.0); #include "COMPLEX.h" b = COMPLEXinit(-2.0, 3.0); c = COMPLEXmult(a, b); (5 + 6i) * (-2 + 3i) = int mand(Complex z) { COMPLEXshow(a); -28 + 3i int i = 0; printf(" * "); Complex c = z; COMPLEXshow(b); while (COMPLEXabs(c) <= 2.0 && i < MAXIT) { printf(" = "); c = COMPLEXadd(COMPLEXmult(c, c), z); COMPLEXshow(c); i++; printf("\n"); } return 0; return i; } } 15 16

Complex Number Data Type: Implementation Complex Number Data Type: Implementation

Write code for interface functions. Write code for interface functions.

complex.c complex.c (cont)

#include double COMPLEXabs(Complex a) { #include implementation and function in return sqrt(a.re * a.re + a.im * a.im); #include "COMPLEX.h" client need to agree on math interface } Complex COMPLEXadd(Complex a, Complex b) { void COMPLEXshow(Complex a) { Complex t; printf("%f + %f i\n", a.re, a.im); t.re = a.re + b.re; } t.im = a.im + b.im; return t; Complex COMPLEXinit(double x, double y) { } Complex t; t.re = x; Complex COMPLEXmult(Complex a, Complex b) { t.im = y; Complex t; return t; t.re = a.re * b.re - a.im * b.im; } t.im = a.re * b.im + a.im * b.re; return t; } 17 18 Compilation Client, Interface, Implementation

Client and implementation both include COMPLEX.h

Compile jointly. %gcc client.c complex.c -lm

Or compile separately. %gcc -c complex.c %gcc -c client.c %gcc client.o complex.o -lm Client Interface Implementation couchpotato.c #include"TV.h" #include tvplasma.c

client needs to know implementation needs to know Unix how to use interface what interface to implement % gcc126 client.c complex.c % a.out (5.00 + 6.00 i) * (-2.00 + 3.00 i) = (-28.00 + 3.00 i) Implementation and client need to agree on interface ahead of time.

19 20

Can Change Implementation Alternate Interface

Can use alternate representation of complex numbers. Interface lists allowable operations on complex data type.

■ Store in polar form: modulus and angle. COMPLEX.h

z = x + i y = r ( cos θ + i sin θ ) = r ei θ typedef struct { double r; polar representation double theta; } Complex; typedef struct { double r; Complex COMPLEXadd (Complex, Complex); double theta; Complex COMPLEXmult (Complex, Complex); } Complex; Complex COMPLEXpow (Complex, Complex); Complex COMPLEXconj (Complex); double COMPLEXabs (Complex); double COMPLEXreal (Complex); double COMPLEXimag (Complex); Complex COMPLEXinit (double, double); void COMPLEXshow (Complex);

21 22 Alternate Implementation Alternate Implementation

Write code for interface functions. Write code for interface functions.

complexpolar.c complexpolar.c

#include "COMPLEX.h" Complex COMPLEXadd(Complex a, Complex b) { #include Complex t; #include double x, y; x = a.r * cos(a.theta) + b.r * cos(b.theta); Complex COMPLEXabs(Complex a) { y = a.r * sin(a.theta) + b.r * sin(b.theta); return a.r; t.r = sqrt(x*x + y*y); } t.theta = arctan(y/x); return t; Complex COMPLEXmult(Complex a, Complex b) { } Complex t; t.r = a.r * b.r; Others are more annoying. t.theta = a.theta + b.theta; }

Some interface functions are now faster and easier to code.

23 24

Multiple Implementations Rational Number Data Type

Usually, several ways to represent and implement a data type. See Assignment 3.

■ You will create data type for Rational numbers.

How to represent complex numbers: rectangular vs. polar? ■ Add associated operations to Rational number data type.

■ Depends on application.

■ Rectangular are better for additions and subtractions. typedef struct { – no need for arctangent int num; int den; ■ Polar are better for multiply and modulus. } Rational; – no need for square root

■ Get used to making tradeoffs.

■ Simple version relatively easy to implement. This example may seem artificial. ■ Improved implementation staves off overflow by: ■ Essential for many real applications. – reducing fractions ■ Crucial software engineering principle. – order of computation

25 26 Conclusions

Basic computer memory abstraction. Lecture P4: Supplemental Notes ■ Indexed sequence of bits.

■ Address = index.

Need higher level abstractions to bridge gap.

■ Array. – homogeneous collection of values

■ Struct. – heterogeneous collection of values

Data type.

■ Set of values and collection of operations on those values.

Client-interface-implementation paradigm.

■ Consistent way to implement data types.

27

Pass By Value, Pass By Reference

Arrays and structs are passed to functions in very DIFFERENT ways.

Pass-by-value: void mystery(Point a) { a.y = 17.0; ■ int, float, char, struct } Unix ■ a COPY of value % a.out is passed to function Point a = {1.0, 2.0}; 1.0 mystery(a); printf("%4.1f\n", a.y);

void mystery(double a[]) { "Pass-by-reference": a[1] = 17.0; Unix ■ arrays }

■ function has direct % a.out access to array double a[] = {1.0, 2.0}; 17.0 elements mystery(a); printf("%4.1f\n", a[1]);

30