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 thecout
andcin
objects from thestd
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), andcircumference
(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 theradius
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. Theendl
manipulator is used to insert a newline character after each output. - The
return 0
statement indicates the successful execution of the program and terminates themain()
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.