C++ Online Compiler
Example: Area Calculator using Functions in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Area Calculator using Functions #include <iostream> #include <cmath> // Required for M_PI and pow() // Define PI if not defined by cmath (some compilers might require it) #ifndef M_PI #define M_PI 3.14159265358979323846 #endif using namespace std; // Function to calculate the area of a circle double calculateCircleArea(double radius) { return M_PI * pow(radius, 2); } // Function to calculate the area of a rectangle double calculateRectangleArea(double length, double width) { return length * width; } // Function to calculate the area of a triangle double calculateTriangleArea(double base, double height) { return 0.5 * base * height; } int main() { // Step 1: Declare variables for user choice and dimensions int choice; double radius, length, width, base, height; // Step 2: Display menu and get user input for shape choice cout << "Choose a shape to calculate its area:" << endl; cout << "1. Circle" << endl; cout << "2. Rectangle" << endl; cout << "3. Triangle" << endl; cout << "Enter your choice (1-3): "; cin >> choice; // Step 3: Use a switch statement to handle different choices switch (choice) { case 1: cout << "Enter the radius of the circle: "; cin >> radius; cout << "The area of the circle is: " << calculateCircleArea(radius) << endl; break; case 2: cout << "Enter the length of the rectangle: "; cin >> length; cout << "Enter the width of the rectangle: "; cin >> width; cout << "The area of the rectangle is: " << calculateRectangleArea(length, width) << endl; break; case 3: cout << "Enter the base of the triangle: "; cin >> base; cout << "Enter the height of the triangle: "; cin >> height; cout << "The area of the triangle is: " << calculateTriangleArea(base, height) << endl; break; default: cout << "Invalid choice. Please enter a number between 1 and 3." << endl; break; } return 0; }
Output
Clear
ADVERTISEMENTS