Calculate area using function overloading - C++

Q. Write a C++ program to calculate the area of triangle, rectangle and circle using function overloading. The program should be menu driven.

Answer:

Function overloading allows to use the same function name for different functions. It is used to enhance the readability of the program. You can change the number of arguments or have different data types of arguments to overload a function.

In the below menu driven program, area() function is overloaded to calculate the area of triangle, rectangle and circle using function overloading.

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

float area(float r)
{
        return(3.14 * r * r);
}
float area(float b,float h)
{
        return(0.5 * b * h);
}
float area(float l,float b)
{
        return (l * b);
}
int main()
{
        float b,h,r,l;
        int ch;

        do
        {
                cout<<"\n\n *****Menu***** \n";
                cout<<"\n 1. Area of Circle";
                cout<<"\n 2. Area of Triangle";
                cout<<"\n 3. Area of Rectangle";
                cout<<"\n 4. Exit";
                cout<<"\n\n Enter Your Choice : ";
                cin>>ch;
                switch(ch)
                {
                        case 1:
                        {
                                cout<<"\n Enter the Radius of Circle : ";
                                cin>>r;
                                cout<<"\n Area of Circle : "<<area(r);
                                break;
                        }
                        case 2:
                        {
                                cout<<"\n Enter the Base & Height of Triangle : ";
                                cin>>b>>h;
                                cout<<"\n Area of Triangle : "<<area(b,h);
                                break;
                        }
                        case 3:
                        {
                                cout<<"\n Enter the Length & Bredth of Rectangle : ";
                                cin>>l>>b;
                                cout<<"\n Area of Rectangle : "<<area(l,b);
                                break;
                        }
                        case 4:
                                exit(0);
                        default:
                                cout<<"\n Invalid Choice... ";
                }
        }while(ch!=4);
        return 0;
}


Output:

1. Area of Circle

area of circle

2. Area of Triangle

area of triangle

3. Area of Rectangle

area of rectangle