//cshapes.h
#define T_CIRCLE 1
#define T_RECTANGLE 2
#define T_TRIANGLE 3
typedef struct CIRCLE_SHAPE
{
short type;
double x,y;
double radius;
} CIRCLE_SHAPE;
typedef struct RECTANGLE_SHAPE
{
short type;
double x1,y1;
double x2,y2;
} RECTANGLE_SHAPE;
typedef struct TRIANGLE_SHAPE
{
short type;
double x1,y1;
double x2,y2;
double x3,y3;
} TRIANGLE_SHAPE;
typedef union SHAPE
{
short type;
CIRCLE_SHAPE circle;
RECTANGLE_SHAPE rectangle;
TRIANGLE_SHAPE triangle;
} SHAPE;
double compute_area(SHAPE *pShape);
void draw_shape(SHAPE *pShape);
//cshapes.c
#include<stdio.h>
#include"cshapes.h"
#include<math.h>
double compute_area(SHAPE *pShape)
{
double area;
switch(pShape->type)
{
case T_CIRCLE:
{
area = M_PI *pShape->circle.radius * pShape->circle.radius;
break;
}
case T_RECTANGLE:
{
area = fabs(
(pShape->rectangle.x2 - pShape->rectangle.x1) *
(pShape->rectangle.y2 - pShape->rectangle.y1)
);
break;
}
case T_TRIANGLE:
{
//double d1,d2,d3;
// Hero's formula
//d1 = (pShape->triangle.x1)
area = 0.5; //TODO:
break;
}
default: printf("Unknown shape\n");
}
return area;
}
void draw_shape(SHAPE *pShape)
{
printf("Draw: ");
switch(pShape->type)
{
case T_CIRCLE:
{
printf("Circle of radius %f at (%f,%f)\n", pShape->circle.radius, pShape->circle.x,pShape->circle.y);
break;
}
case T_RECTANGLE:
{
printf("Rectangle with corners: (%f, %f)and (%f,%f)\n", pShape->rectangle.x1, pShape->rectangle.y1,pShape->rectangle.x2, pShape->rectangle.y2);
break;
}
case T_TRIANGLE:
{
printf("Triangle with coordinate: (%f,%f)", pShape->triangle.x1, pShape->triangle.y1);
break;
}
default:
printf("Unknown shape in draw!\n");
}
}
//main.c
#include<stdio.h>
#include "cshapes.h"
int main()
{
int i;
SHAPE s[3];
s[0].type = T_RECTANGLE;
s[0].rectangle.x1 = 80.0;
s[0].rectangle.y1 = 30.0;
s[0].rectangle.x2 = 120.0;
s[0].rectangle.y2 = 50.0;
s[1].type = T_CIRCLE;
s[1].circle.x = 200.0;
s[1].circle.y = 100.0;
s[1].circle.radius = 50.0;
s[2].type = T_TRIANGLE;
s[2].triangle.x1 = 4.0;
s[2].triangle.y1 = 4.0;
s[2].triangle.x2 = 4.0;
s[2].triangle.y2 = 4.0;
s[2].triangle.x3 = 4.0;
s[2].triangle.y3 = 4.0;
for (i = 0; i < 3; ++i)
printf("Areas of shape[%d] = %f\n", i, compute_area(&s[i]));
for (i = 0; i < 3; ++i)
draw_shape(&s[i]);
return 0;
}
How to run the program?
$gcc -lm -c cshapes.c -o cshapes.o
$gcc cshapes.o main.c -o shapes
$./shapes
Foot Note:
-lm links math library.
-c compile only option to generate object file.