Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

1: #include <iostream>

2: #include <cmath>
3:
4: // Abstract base class representing a shape
5: class Shape {
6: public:
7: // Pure virtual function to calculate the area of a shape
8: virtual double calculateArea() const = 0;
9:
10: // Virtual destructor to ensure proper cleanup of derived classes
11: virtual ~Shape() {}
12: };
13:
14: // Derived class representing a rectangle
15: class Rectangle : public Shape {
16: private:
17: double length;
18: double width;
19:
20: public:
21: Rectangle(double length, double width) : length(length), width(width) {}
22:
23: double calculateArea() const override {
24: return length * width;
25: }
26: };
27:
28: // Derived class representing a circle
29: class Circle : public Shape {
30: private:
31: double radius;
32:
33: public:
34: Circle(double radius) : radius(radius) {}
35:
36: double calculateArea() const override {
37: return M_PI * pow(radius, 2);
38: }
39: };
40:
41: // Derived class representing a triangle
42: class Triangle : public Shape {
43: private:
44: double base;
45: double height;
46:
47: public:
48: Triangle(double base, double height) : base(base), height(height) {}
49:
50: double calculateArea() const override {
51: return 0.5 * base * height;
52: }
53: };
54:
55: int main() {
56: int choice;
57: double dimension1, dimension2;
58:
59: do {
60: // Display menu
61: std::cout << "----- Shape Area Calculator -----" << std::endl;
62: std::cout << "1. Rectangle" << std::endl;
63: std::cout << "2. Circle" << std::endl;
64: std::cout << "3. Triangle" << std::endl;
65: std::cout << "0. Exit" << std::endl;
66: std::cout << "Enter your choice: ";
67: std::cin >> choice;
68:
69: switch (choice) {
70: case 1: {
71: // Rectangle
72: std::cout << "Enter length: ";
73: std::cin >> dimension1;
74: std::cout << "Enter width: ";
75: std::cin >> dimension2;
76: Shape* rectangle = new Rectangle(dimension1, dimension2);
77: std::cout << "Area: " << rectangle->calculateArea() << std::endl;
78: delete rectangle;
79: break;
80: }
81:
82: case 2: {
83: // Circle
84: std::cout << "Enter radius: ";
85: std::cin >> dimension1;
86: Shape* circle = new Circle(dimension1);
87: std::cout << "Area: " << circle->calculateArea() << std::endl;
88: delete circle;
89: break;
90: }
91:
92: case 3: {
93: // Triangle
94: std::cout << "Enter base: ";
95: std::cin >> dimension1;
96: std::cout << "Enter height: ";
97: std::cin >> dimension2;
98: Shape* triangle = new Triangle(dimension1, dimension2);
99: std::cout << "Area: " << triangle->calculateArea() << std::endl;
100: delete triangle;
101: break;
102: }
103:
104: case 0:
105: std::cout << "Exiting..." << std::endl;
106: break;
107:
108: default:
109: std::cout << "Invalid choice. Please try again." << std::endl;
110: break;
111: }
112:
113: std::cout << std::endl;
114:
115: } while (choice != 0);
116:
117: return 0;
118: }
119:

You might also like