C++ Program to Find the Surface Area and Volume of a Sphere

Surface Area and Volume of a Sphere in C++

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², where r is the radius of the sphere.
  • Volume: The volume of a sphere is given by the formula: (4/3) × Ï€ × r³, where r 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 like pow() (to calculate powers) and M_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², where pow(radius, 2) calculates .
    • The volume is calculated using the formula (4/3) × Ï€ × r³, where pow(radius, 3) calculates .
  • Output: The calculated surface area and volume are displayed using cout.