C++ area & circumference of a circle

To calculate the area and circumference of a circle in C++, you can use the following code:

#include <iostream>
using namespace std;

int main() {
   double radius, area, circumference;

   cout << "Enter the radius of the circle: ";
   cin >> radius;

   area = 3.14159  radius  radius;
   circumference = 2  3.14159  radius;

   cout << "The area of the circle is: " << area << endl;
   cout << "The circumference of the circle is: " << circumference << endl;

   return 0;
}

Explanation:

  • The code begins by including the necessary header file iostream, which provides input/output stream functionality.
  • The using namespace std line allows us to use the cout and cin objects from the std namespace without specifying the namespace each time.
  • In the main() function, we define three variables: radius (to store the radius entered by the user), area (to store the calculated area), and circumference (to store the calculated circumference).
  • We then prompt the user to enter the radius of the circle using the cout object and the << operator.
  • The cin object and the >> operator are used to read the user's input and store it in the radius variable.
  • The area of the circle is calculated using the formula area = 3.14159 radius radius.
  • The circumference of the circle is calculated using the formula circumference = 2 3.14159 radius.
  • Finally, the calculated area and circumference are displayed to the user using the cout object and the << operator. The endl manipulator is used to insert a newline character after each output.
  • The return 0 statement indicates the successful execution of the program and terminates the main() function.

This code allows the user to input the radius of a circle and calculates and displays its area and circumference. The formulas used are based on the mathematical properties of circles.