Challenge: Shape Areas

Lab C++ Intermediate 20 points

Write an abstract class Shape with a pure virtual double area() const, and two children: Rect (width, height) and Tri (base, height, area = base × height / 2). Read n lines like rect 3 4 or tri 6 2, store pointers to the shapes in a vector and print every area with 1 decimal place, then the total.

Input

n, then n lines.

Output

12.0
6.0
Total: 18.0

Example

Input

2
rect 3 4
tri 6 2

Output

12.0
6.0
Total: 18.0
Sample input available Sample output available
Editor
C++

Hints

virtual double area() const = 0; makes Shape abstract.

Create shapes with new Rect(x, y) and keep them in a vector<Shape*>.

Don't forget to delete them at the end.

Solution explanation

The loop calls area() through a Shape* and each object runs its own version.

Show solution
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;

class Shape {
public:
    virtual double area() const = 0;
    virtual ~Shape() {}
};

class Rect : public Shape {
    double w, h;
public:
    Rect(double width, double height) : w(width), h(height) {}
    double area() const override { return w * h; }
};

class Tri : public Shape {
    double b, h;
public:
    Tri(double base, double height) : b(base), h(height) {}
    double area() const override { return b * h / 2; }
};

int main() {
    int n;
    cin >> n;
    vector<Shape*> shapes;
    for (int i = 0; i < n; i++) {
        string kind;
        double x, y;
        cin >> kind >> x >> y;
        if (kind == "rect") {
            shapes.push_back(new Rect(x, y));
        } else {
            shapes.push_back(new Tri(x, y));
        }
    }
    double total = 0;
    cout << fixed << setprecision(1);
    for (Shape* s : shapes) {
        cout << s->area() << "\n";
        total += s->area();
    }
    cout << "Total: " << total << "\n";
    for (Shape* s : shapes) {
        delete s;
    }
    return 0;
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD