C++ Code Example: volume and surface area of a ball

The code calculates the volume and surface area of a sphere. The sphere is defined by its radius r which is entered by the user. The code consists of three parts:

  1. getVolume function: This function calculates the volume of the sphere. The volume of a sphere is given by (4 * pi * r^3) / 3. In the function, pow(base, exponent) is used to calculate r^3. The constant M_PI is defined in <math.h> library and it is used to represent the value of pi.
  2. getSurfaceArea function: This function calculates the surface area of the sphere. The surface area of a sphere is given by 4 * pi * r^2. In the function, pow(base, exponent) is used to calculate r^2.
  3. Main function: This function is the starting point of the code. It first prompts the user to enter the value of the radius r. Then, it calls the getVolume and getSurfaceArea functions to calculate the volume and surface area of the sphere, respectively. Finally, it rounds the values of volume and surface area and outputs them.

Note: The round function is used to round the values of volume and surface area to the nearest integer.

#include &lt;iostream&gt;
#include &lt;math.h&gt;
using namespace std;


double getVolume(double r) {
    // Math.pow(base, exponent): Returns base raised to the power exponent
    return (4 * M_PI * pow(r, 3)) / 3;
}

double getSurfaceArea(double r) {
    return 4 * M_PI * pow(r, 2);
}

int main(){
    double r, area, volume;

    cout << "Please enter radius: ";
    cin >> r;

    area = getSurfaceArea(r);
    volume = getVolume(r);

    cout << "Volume: " << round(volume) << endl;
    cout << "Surface Area: " << round(area);

    return 0;
}
Output
Please enter radius: 2
Volume: 34
Surface Area: 50