C++ Online Compiler
Example: Circle Area Calculator in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Circle Area Calculator #include <iostream> // Required for input/output operations #include <cmath> // Required for M_PI (if available) or pow() function // Define PI as a constant for better precision and readability // Alternatively, use M_PI from <cmath> or define as acos(-1.0) const double PI = 3.14159265358979323846; // Function to calculate the area of a circle // It takes the radius (double) as input // It returns the calculated area (double) double calculateCircleArea(double radius) { // Step 1: Check for a valid radius if (radius < 0) { std::cout << "Error: Radius cannot be negative." << std::endl; return 0.0; // Return 0 or an error indicator for invalid radius } // Step 2: Apply the formula: Area = PI * radius * radius // We can use radius * radius or pow(radius, 2) double area = PI * radius * radius; return area; // Return the calculated area } int main() { // Step 1: Declare a variable to store the radius double radius; // Step 2: Prompt the user to enter the radius std::cout << "Enter the radius of the circle: "; // Step 3: Read the radius from user input std::cin >> radius; // Step 4: Call the function to calculate the area // Store the returned value in a variable double areaOfCircle = calculateCircleArea(radius); // Step 5: Display the result if the radius was valid if (radius >= 0) { std::cout << "The area of the circle is: " << areaOfCircle << std::endl; } return 0; // Indicate successful program execution }
Output
Clear
ADVERTISEMENTS