WAP to calculate area of circle(radius), rectangle(l,b), triangle(a,b,c) using function overloading c++.
Function overloading in C++ is a feature in c++ where two or more functions can have the same name but different parameters.
When a function name is overloaded with different jobs then it is called function overloading.
The overloaded function may or may not have a different data type but they must have different arguments.
// WAP to calculate area of circle(radius), rectangle(l,b), triangle(a,b,c) using function overloading #include<iostream> #include<cmath> using namespace std; void area(float, float, float); void area(float, float); void area(float); int main() { int choice; float r, l, b, x, y, z; cout<<"Whose area you want to calculate?"<<endl; cout<<"1 - Area of circle"<<endl; cout<<"2 - Area of rectangle"<<endl; cout<<"3 - Area of triangle"<<endl; cin>>choice; switch (choice) { case 1: cout<<"Enter the radius of circle."<<endl; cin>>r; area(r); break; case 2: cout<<"Enter the sides of rectangle."<<endl; cin>>l>>b; area(l,b); break; case 3: cout<<"Enter the sides of triangle."<<endl; cin>>x>>y>>z; area(x,y,z); break; default: cout<<"Choose from 1, 2, 3"<<endl; break; } return 0; } void area(float r) { float pi = 3.14; cout<<"Area of circle is "<<pi*r*r<<endl; } void area(float l, float b) { cout<<"Area of rectangle is "<<l*b<<endl; } void area(float a, float b, float c) { float s, area; if((a+b)>c && (b+c)>a && (a+c)>b) { s = (a+b+c)/2; area = sqrt(s*(s-a)*(s-b)*(s-c)); cout<<"Area of triangle is "<<area<<endl; } else cout<<"Triangle does not form"<<endl; }
Also check out: Add and Subtract using a return function in c++
Output:
Whose area do you want to calculate?
1 – Area of a circle
2 – Area of rectangle
3 – Area of triangle
1
Enter the radius of a circle.
1
Area of circle is 3.14
Whose area do you want to calculate?
1 – Area of a circle
2 – Area of rectangle
3 – Area of triangle
2
Enter the sides of a rectangle.
2
2
Area of rectangle is 4
Whose area do you want to calculate?
1 – Area of a circle
2 – Area of rectangle
3 – Area of triangle
3
Enter the sides of a triangle.
3
3
3
The area of a triangle is 3.89711
Whose area do you want to calculate?
1 – Area of a circle
2 – Area of rectangle
3 – Area of triangle
0
Choose from 1, 2, 3