C++ Program to Find the Surface Area and Volume of a Sphere
Introduction
A sphere is a three-dimensional geometric object that is perfectly round, similar to a ball. In mathematics, calculating the surface area and volume of a sphere is a fundamental concept. These calculations are based on the radius of the sphere, which is the distance from its center to any point on its surface.
This article explains the formulas for the surface area and volume of a sphere, provides a simple C++ program to perform these calculations, and explains the code step by step.
Formula
The formulas to calculate the surface area and volume of a sphere are as follows:
-
Surface Area: The surface area of a sphere is given by the formula:
4 × Ï€ × r²
, wherer
is the radius of the sphere. -
Volume: The volume of a sphere is given by the formula:
(4/3) × Ï€ × r³
, wherer
is the radius of the sphere.
Here, π
(pi) is a mathematical constant approximately equal to 3.14159.
Code
Below is a simple C++ program to calculate the surface area and volume of a sphere based on user-provided radius.
#include <iostream> #include <cmath> using namespace std; int main() { double radius, surfaceArea, volume; // Input radius cout << "Enter the radius of the sphere: "; cin >> radius; // Calculating surface area and volume surfaceArea = 4 * M_PI * pow(radius, 2); volume = (4.0 / 3) * M_PI * pow(radius, 3); // Output results cout << "Surface Area of the sphere: " << surfaceArea << " square units" << endl; cout << "Volume of the sphere: " << volume << " cubic units" << endl; return 0; }
Output
When you run the program and input the radius of the sphere, it will calculate and display the surface area and volume. Here's an example of how the output might look:
Enter the radius of the sphere: 5 Surface Area of the sphere: 314.159 square units Volume of the sphere: 523.599 cubic units
Explanation
Let's break down the program step by step:
-
Header Files: The program includes
<iostream>
for input and output operations and<cmath>
for mathematical functions likepow()
(to calculate powers) andM_PI
(for the value of π). -
Input: The user is prompted to enter the radius of the sphere. This value is stored in the variable
radius
. -
Calculations:
-
The surface area is calculated using the formula
4 × Ï€ × r²
, wherepow(radius, 2)
calculatesr²
. -
The volume is calculated using the formula
(4/3) × Ï€ × r³
, wherepow(radius, 3)
calculatesr³
.
-
The surface area is calculated using the formula
-
Output: The calculated surface area and volume are displayed using
cout
.