Initial commit
This commit is contained in:
13
Final/FinalCode/polymorphism/polymorphism.c
Normal file
13
Final/FinalCode/polymorphism/polymorphism.c
Normal file
@ -0,0 +1,13 @@
|
||||
#include <stdio.h>
|
||||
#include "triangle.h"
|
||||
#include "square.h"
|
||||
#include "shape.h"
|
||||
|
||||
int main(){
|
||||
Shape *triangle = newTriangle(20);
|
||||
Shape *square = newSquare(20);
|
||||
printf("Triangle area of perimeter 20: %f\n", triangle->area(triangle));
|
||||
printf("Square area of perimeter 20: %f\n", square->area(square));
|
||||
return 0;
|
||||
}
|
||||
|
10
Final/FinalCode/polymorphism/shape.h
Normal file
10
Final/FinalCode/polymorphism/shape.h
Normal file
@ -0,0 +1,10 @@
|
||||
#ifndef shape_h
|
||||
#define shape_h
|
||||
|
||||
typedef struct{
|
||||
int numSides;
|
||||
double perimeter;
|
||||
double (*area) ();
|
||||
} Shape;
|
||||
|
||||
#endif
|
24
Final/FinalCode/polymorphism/square.h
Normal file
24
Final/FinalCode/polymorphism/square.h
Normal file
@ -0,0 +1,24 @@
|
||||
#ifndef square_h
|
||||
#define square_h
|
||||
|
||||
#include <stdlib.h>
|
||||
#include "shape.h"
|
||||
|
||||
double squareArea(Shape* square) {
|
||||
double side = square->perimeter / 4;
|
||||
double area = side * side;
|
||||
return area;
|
||||
}
|
||||
|
||||
Shape* newSquare(double perimeter) {
|
||||
Shape* square = malloc(sizeof(Shape));
|
||||
square->numSides = 3;
|
||||
square->perimeter = perimeter;
|
||||
square->area = squareArea;
|
||||
return square;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
|
24
Final/FinalCode/polymorphism/triangle.h
Normal file
24
Final/FinalCode/polymorphism/triangle.h
Normal file
@ -0,0 +1,24 @@
|
||||
#ifndef triangle_h
|
||||
#define triangle_h
|
||||
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <math.h>
|
||||
#include "shape.h"
|
||||
|
||||
double triangleArea(Shape* triangle) {
|
||||
double side = triangle->perimeter / 3;
|
||||
double area = (sqrt(3) / 4) * (side * side);
|
||||
return area;
|
||||
}
|
||||
|
||||
Shape* newTriangle(double perimeter) {
|
||||
Shape* triangle = malloc(sizeof(Shape));
|
||||
triangle->numSides = 4;
|
||||
triangle->perimeter = perimeter;
|
||||
triangle->area = triangleArea;
|
||||
return triangle;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
Reference in New Issue
Block a user