shape2

shape2.c  [download]

/* 
 * First example: shapes
 * 2. Modularized, uses typedefs, but still in C
 *
 * RunStuff:: gcc THISFILE
 */

#include <stdio.h>

/*
 * Type definitions
 */
typedef struct { //*1 Data definitions: Use structs to hold the data
	int x, y, wid, ht; //*1
} Rect; //*1

typedef struct { //*1
	int x, y, rad; //*1
} Circle; //*1

/*
 * Data definitions
 */
Rect r1, r2;
Circle c1;

/* 
 * Procedure definitions
 */
void drawRect (Rect r) { //*2 Procedure definitions: Pass struct as parameter
	printf ("Drawing rectangle at %d, %d, %d, %d\n", r.x, r.y, r.wid, r.ht);
}

void drawCircle (Circle c) { //*2
	printf ("Drawing circle at %d, %d, radius = %d\n", c.x, c.y, c.rad);
}

float areaRect (Rect r) { //*2
	return (float) (r.wid * r.ht);
}

float areaCircle (Circle c) { //*2
	return (float) (c.rad * c.rad * 3.14159);
}

int main () {
	/*
	 * Set the locations of the 3 objects
	 */
	r1.x = 10; r1.y = 10; //*3 Set the data
	r1.wid = 50; r1.ht = 50; //*3

	r2.x = 80; r2.y = 10; //*3
	r2.wid = 10; r2.ht = 100; //*3

	c1.x = 35; c1.y = 90; //*3
	c1.rad = 10; //*3

	/*
	 * Draw them
	 */
	drawRect (r1); //*4 Call the procedures
	drawRect (r2); //*4
	drawCircle (c1); //*4

	/*
	 * Compute and print total area
	 */
	printf ("Total area = %f\n",
		areaRect (r1) + areaRect (r2) + areaCircle (c1)); //*4

	return 0;
}