Circumference and circular area

This C++ code calculates the circumference and area of a circle based on a given radius.

Code Example

#include <iostream>
#include <math.h>
using namespace std;

#define _USE_MATH_DEFINES

int main () {
    float r, area, circumference;

    cout << "Please enter radius: ";
    cin >> r;

    // calculation of circumference
    circumference = 2 * M_PI * r;

    // calculation of circular area
    // pow(base, exponent): Returns base raised to the power exponent
    area = M_PI * pow(r, 2);

    cout << "Circumference: " << circumference << endl;
    cout << "Circular Area: " << area << endl;
}

Output

Please enter radius: 7
Circumference: 43.9823
Circular Area: 153.938

Code Explanation

1. Preprocessor Directive:

#define _USE_MATH_DEFINES
  • This preprocessor directive enables the definition of several mathematical constants in C++. When this line is included before including cmath or math.h, constants such as M_PI (which represents the value of π) become available. This is particularly useful since M_PI is used to calculate the circumference and area of the circle.

2. Variable Declaration and User Input:

float r, area, circumference;
cout << "Please enter radius: ";
cin >> r;
  • Here, three variables of type float are declared: r, area, and circumference. The variable r will store the radius of the circle.
  • The program prompts the user to input the radius of the circle, which is then read and stored in r using cin.

3. Calculate the Circumference:

circumference = 2 * M_PI * r;
  • The circumference of the circle is calculated using the formula 2𝜋𝑟2πr. M_PI provides the value of π, and r is the radius entered by the user. The result is stored in the circumference variable.

4. Calculate the Circular Area:

area = M_PI * pow(r, 2);
  • The area of the circle is calculated using the formula 𝜋𝑟2πr2. The pow function is used to square the radius (pow(r, 2)), which is then multiplied by π (M_PI) to find the area. The result is stored in the area variable.

5. Output the Results:

cout << "Circumference: " << circumference << endl;
cout << "Circular Area: " << area << endl;
  • These lines print the calculated values of the circumference and area to the standard output. endl is used after each output to insert a newline character and flush the stream, ensuring that all output is immediately displayed.