Program to Calculate the Area of a Circle in C++

Calculating the Area of a Circle

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.

Method 1: Using Basic Arithmetic

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;
}
            
Input: 5.0
Output: Area of the circle: 78.54

Method 2: Using a Function

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;
}
            
Input: 7.0
Output: Area of the circle: 153.94

Method 3: Using Recursion

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;
}
            
Input: 4.0
Output: Area of the circle: 50.27