Skip to main content

Area of triangle and rectangle program

Short answer

Overload a function area() for triangle using Heron’s formula s=(a+b+c)/2 and area= sqrt(s(s-a)(s-b)(s-c)). For rectangle, define area(length, breadth=0) that returns length*breadth; if breadth is 0, treat as square. Three arguments call triangle version, one or two call rectangle version.

Write a program to find the area of triangle (when three sides are given) and area of rectangle using function overloading and default argument.

Plan: overload area(). The triangle version takes three sides and uses Heron's formula, s = (a+b+c)/2 and area = √(s(s-a)(s-b)(s-c)). The rectangle version takes length and breadth, where breadth has a default value (making a square when only one value is given).

#include <iostream>
#include <cmath>
using namespace std;

// Area of triangle: three sides (Heron's formula)
float area(float a, float b, float c)
{
    float s = (a + b + c) / 2;
    return sqrt(s * (s - a) * (s - b) * (s - c));
}

// Area of rectangle: breadth has a default (= length -> square)
float area(float l, float b = 0)
{
    if (b == 0)
        b = l;
    return l * b;
}

int main()
{
    float a, b, c, l, w;
    cout << "Enter three sides of triangle: ";
    cin >> a >> b >> c;
    if (a + b > c && b + c > a && a + c > b)
        cout << "Area of triangle = " << area(a, b, c) << endl;
    else
        cout << "Not a valid triangle" << endl;

    cout << "Enter length and breadth of rectangle: ";
    cin >> l >> w;
    cout << "Area of rectangle = " << area(l, w) << endl;
    cout << "Area when only length given = " << area(l) << endl;
    return 0;
}

Sample output

Enter three sides of triangle: 3 4 5
Area of triangle = 6
Enter length and breadth of rectangle: 5 2
Area of rectangle = 10
Area when only length given = 25

The compiler chooses the version by the number of arguments (3 arguments gives triangle; 1 or 2 gives rectangle), so there is no ambiguity.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 3 questions →