Using Function Overloading Calculate area of Triangle, Circle and Rectangle in C++

Using Function Overloading Calculate area of Triangle, Circle and Rectangle

Using the concept of function overloading we will write function for calculating the area of Triangle, Circle and Rectangle.

Function Overloading – Function overloading means two or more function having same name and can take different arguments and gets called accordingly. Function Overloading is the concept of polymorphism. It is Compile time polymorphism.

Note :- We have find the area of Triangle using Heron’s Formula If you don’t know about it please refer this link – Heron’s Formula

Now Lets see the C++ program to calculate Area of Triangle, Circle and Rectangle using Function Overloading.

#include<iostream>
#include<math.h>
using namespace std;

float area(float r){
    return (3.14*r*r);	
}
float area(float length, float breadth){
    return (length*breadth);
}
float area(float s1,float s2, float s3){
    float s, a;
    s = (s1+s2+s3)/2;
    a = sqrt(s*(s-s1)*(s-s2)*(s-s3));
    return a;
}


int main(){
    
    float radius, length, breadth, a,b,c;
    cout << "Enter the radius of Circle: ";
    cin >> radius;
    cout << "Area of Circle is: ";
    //here we pass the single argument in area then it will select the function with single argument
    cout << area(radius) << endl; 
    
    cout << "Enter the length and breadth of Rectangle: ";
    cin >> length >> breadth;
    cout << "Area of Rectangle is: ";
    //here we pass 2 arguments in area then it will select the function with 2 arguments
    cout << area(length,breadth) << endl;
    
    cout << "Enter the 3 sides of the triangle: ";
    cin >> a >> b >> c;
    cout << "Area of Triangle is: ";
    //here we pass 3 arguments in area then it will select the function with 3 arguments
    cout << area(a,b,c) << endl;
    
    return 0;
}

Output :-

Enter the radius of Circle: 7
Area of Circle is: 153.86
Enter the length and breadth of Rectangle: 20 30
Area of Rectangle is: 600
Enter the 3 sides of the triangle: 6 7 8
Area of Triangle is: 20.3332

Leave a Reply