Write a C++ program to calculate the area of circle, rectangle and square using function overloading.
What is Function Overloading? 🤔
C++ allows us to have multiple definitions of same name function in same scope but their signature must be different, is known as Function Overloading.
Tutorial 📺
Watch the tutorial to understand how to solve this problem. 😇
Steps 🪜
To Find Area using Function Overloading
- Declare and define 3 definition of area() function to calculate the area of circle, rectangle and square.
- In Circle’s area() function, display a message to ask user to input radius of circle. Next, display the area of circle, after accepting the radius of circle.
- Square’s area() function should take an argument of floating point type and simply displays the area of square based on the accepted argument.
- Rectangle’s area() function should take two arguments of floating point type and display the area of rectangle based on the accepted arguments.
- In main() function, simply call the area() functions to find the area of circle, rectangle and square.
Code 💻
#include <iostream.h>
#include <conio.h>
// Area of Circle
void area()
{
float r = 0;
cout << "Please enter the radius: ";
cin >> r;
cout << "\nArea of Circle: " << 3.14 * r * r << endl;
}
// Area of Square
void area(float s)
{
cout << "\nArea of Square: " << s * s << endl;
}
// Area of Rectangle
void area(float l, float w)
{
cout << "\nArea of Rectangle: " << l * w << endl;
}
/*
NOTE: Some compilers may not support clrscr() and getch() functions.
In that case, comment them.
*/
void main()
{
clrscr();
area(); // Circle
area(2.0f); // Square
area(2.0f, 3.0f); // Rectangle
getch();
}
Output 😍
Please enter the radius: 3
Area of Circle: 28.26
Area of Square: 4
Area of Rectangle: 6
Comments