C++ Online Compiler
Example: Area Calculator with Function Overloading in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Area Calculator with Function Overloading #include <iostream> #include <cmath> // Required for M_PI on some systems, or define PI manually // Define PI constant const double PI = 3.14159265358979323846; // Function to calculate the area of a circle // Takes one double argument (radius) double area(double radius) { return PI * radius * radius; } // Function to calculate the area of a rectangle // Takes two double arguments (length, width) double area(double length, double width) { return length * width; } // Function to calculate the area of a triangle // Takes two double arguments (base, height) double area(double base, double height) { return 0.5 * base * height; } int main() { // Step 1: Calculate and display the area of a circle double circleRadius = 5.0; double circleArea = area(circleRadius); // Calls area(double) std::cout << "Area of Circle with radius " << circleRadius << ": " << circleArea << std::endl; // Step 2: Calculate and display the area of a rectangle double rectLength = 10.0; double rectWidth = 5.0; double rectangleArea = area(rectLength, rectWidth); // Calls area(double, double) for rectangle std::cout << "Area of Rectangle with length " << rectLength << " and width " << rectWidth << ": " << rectangleArea << std::endl; // Step 3: Calculate and display the area of a triangle double triBase = 10.0; double triHeight = 5.0; double triangleArea = area(triBase, triHeight); // Calls area(double, double) for triangle std::cout << "Area of Triangle with base " << triBase << " and height " << triHeight << ": " << triangleArea << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS