Write a C++ program to calculate the area of circle, rectangle and square using function overloading.

As given in the program definition, we have to find area using function overloading.

What is Function Overloading? 🤔

C++ allows us to have multiple definitions of the same name function within the same scope but their signature must be different, this is known as Function Overloading.

Tutorial 📺

Steps 🪜

To Find Area using Function Overloading

  1. Declare and define three definitions of the area() function to calculate the area of circle, rectangle, and square.
  2.  Within the circle’s area() function, display a message to ask the user to input the radius of circle. Now, display the area of the circle after accepting the radius from the user.
  3.  Square’s area() function should accept an argument of floating point data type and display the area of the square based on the accepted argument.
  4. Rectangle’s area() function should accept two arguments of floating point data type and display the area of the rectangle based on the accepted values.
  5. In the main() function, 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.

int main()
{
  clrscr();
  area(); // Circle
  area(2.0f); // Square
  area(2.0f, 3.0f); // Rectangle
  getch();
  return 0;
}

Output 😃

Please enter the radius: 3

Area of Circle: 28.26

Area of Square: 4

Area of Rectangle: 6

Categorized in: