EXERCISES ON STRUCTURES READING ------- Kernighan and Ritchie, 6.1 Sedgewick, 69-80 SUPPLEMENTAL READING -------------------- Deitel and Deitel, 10.1-10.6 EXERCISES --------- 1. What is wrong with the following C declarations? A. struct ex ( float a, b ) B. struct ex { float a, float b }; C. struct ex { float a; int b } D. struct ex { int a; float b; }; E. struct ex { int a; int b; } 2. What is the difference between the following two programs? #include struct interval { float a; float b; }; void main() { struct interval test; test.a = .25; test.b = .75; printf("[%6.4f %6.4f]\n", test.a, test.b); } typedef struct { float a; float b; } interval; void main() { interval test; test.a = .25; test.b = .75; printf("[%6.4f %6.4f]\n", test.a, test.b); } 3. Provide implementations of a function NEW (return an interval, given two floats) and a function SHOW (print an interval) so that the following "main" is functionally equivalent to the two programs in exercise 2. main() { interval test = NEW(.25, .75); show(test); } 4. Write a function that returns 1 if a float falls within an interval, 0 if not. Use the type "interval" defined in exercise 3, and the function prototype "int in(float, interval);" 5. Define a type for rectangles that are parallel to the axes in a Cartesian coordinate sysytem. Use the type "interval" from exercise 3. 6. Write a function that returns 1 if a point falls within a rectangle, 0 otherwise. Use the function prototype "int inrect(point, rect);" and define your own point type. 7. What is wrong with the following C declarations? A. typedef struct { float x; float y } point; B. typedef { float x; float y; } point; C. typedef struct { float x; float y; }; D. typedef struct { float x; float y; } point; . . ANSWERS TO EXERCISES ON STRUCTURES 1. A. Everything. Need braces, not parens; semicolons, not comma. B. Comma is wrong (need semicolons). C. Need semicolon after b. D. Nothing wrong. This one is OK. E. Need semicolon at end. 2. None 3. #include typedef struct { float a; float b; } interval; interval NEW(float a, float b) { interval t; t.a = a; t.b = b; return t; } void show(interval t) { printf("[%6.4f %6.4f]\n", t.a, t.b); } 4. int in(float p, interval t) { if (p < t.a) return 0; if (p > t.b) return 0; return 1; } 5. typedef struct { interval x; interval y; } rect; 6. typedef struct { float x; float y; } point; int inrect(point p, rect t) { return in(p.x, t.x) && in(p.y, t.y); } 7. A. Semicolon missing after "y". B. "struct" missing; some type must follow "typedef". C. Useless because there is no name for the typedef D. Nothing wrong. This one is OK.