The area of a circle is calculated using the formula:
Area = π × r², where 'r' is the radius of the circle.
We will explore three different methods to calculate the area of a circle in C++ programming.
This method directly computes the area using the formula.
#include <iostream> #define PI 3.14159 using namespace std; int main() { float radius, area; cout << "Enter the radius of the circle: "; cin >> radius; area = PI * radius * radius; cout << "Area of the circle: " << area << endl; return 0; }
This method uses a function to calculate and return the area.
#include <iostream> #define PI 3.14159 using namespace std; float calculate_area(float radius) { return PI * radius * radius; } int main() { float radius; cout << "Enter the radius of the circle: "; cin >> radius; cout << "Area of the circle: " << calculate_area(radius) << endl; return 0; }
This method demonstrates recursion, though recursion is not typically needed for simple mathematical operations.
#include <iostream> #define PI 3.14159 using namespace std; float recursive_area(float radius, int times) { if (times == 0) return PI * radius * radius; return recursive_area(radius, times - 1); } int main() { float radius; cout << "Enter the radius of the circle: "; cin >> radius; cout << "Area of the circle: " << recursive_area(radius, 1) << endl; return 0; }