Calculate the Area of a Circle in C++
Master the use of constants and mathematical formulas by building a program that computes the area of a circle using a radius provided by the user.
Logic and Constants
The const Keyword
Using const double PI ensures that the value of π cannot be modified during program execution, preventing errors in geometric calculations.
Area Formula
We apply the formula $A = \pi \cdot r^2$ by multiplying the radius by itself: PI * radius * radius.
Key Concepts Learned:
- Constants: Protecting fixed values with
const. - Precision: Using
doublefor accurate scientific results. - User Interaction: Dynamic input via
cin.
Course:
Introduction to C++
Step-by-Step Objective
- Define a
const doublefor PI (3.14159). - Request the circle's radius from the user.
- Execute the calculation:
area = PI * radius * radius. - Output the result with a descriptive message.
C++ Solution
circle_area.cpp
C++ Beginners
#include <iostream>
using namespace std;
int main() {
const double PI = 3.14159;
double radius, area;
cout << "Enter the radius of the circle: ";
cin >> radius;
// Calculation logic
area = PI * radius * radius;
cout << "The area of the circle is: " << area << endl;
return 0;
}
Console Output:
Enter the radius of the circle: 3
The area of the circle is: 28.2743
Constants & Geometric Logic