Open In App

JavaScript Program to Find Volume of Sphere

To calculate the JavaScript Program to Find the Volume of the Sphere. We use the direct formula to calculate the volume of the sphere. A sphere is a perfectly round geometrical object in three-dimensional space. It is defined as the set of all points in space that are equidistant from a given point called the center.

Example:

V = (4/3)πr^3
where,
π is constant, value 3.141592653589793
r is radius of sphere

Using direct formula

The code defines a function sphereVolume that takes one parameter i.e. "radius".Inside the function, it calculates the volume of a sphere using the formula "V = (4/3)πr^3", where "r" is the radius of the sphere. The Math. pow() function is used to calculate the cube of the radius.It then assigns the result to the variable "volume" and returns it. Finally, the code calculates the volume of a sphere with a given radius and logs the result to the console.

Example: JavaScript program to find the volume of a Sphere.

// using formula

function calculateSphereVolume(radius) {
    const volume = (4 / 3) * Math.PI * Math.pow(radius, 3);
    return volume;
}

const radius = 3;
const volume = 
    calculateSphereVolume(radius);
console.log(
    "Volume of the sphere with radius", radius, "is", volume.toFixed(2));                    

Output
Volume of the sphere with radius 3 is 113.10

Time Complexity: O(1).

Space Complexity: O(1).

Using Arrow Function

We will cerate an arrow function which takes the radius of the sphere as input and returns the volume of the sphere using the formula : Volume of sphere = (4/3)πr^3. Now create main function which is responsible for prompting the user to input the radius, validating the input, and calculating the volume using above function. Return the calculated volume.

Example: JavaScript program to find the volume of a Sphere using arrow function

const SphereVolume = 
    (radius) => (4 / 3) * Math.PI * Math.pow(radius, 3);

const main = () => {

    const radius = 3;

    // checking valid input
    if (isNaN(radius) || radius < 0) {
        console.log(" not a valid radius");
        return;
    }


    const volume = SphereVolume(radius);

    console.log(
        `The volume of the sphere with radius ${radius} units is : 
            ${volume.toFixed(2)} cubic units.`);
};

main();

Output
The volume of the sphere with radius 3 units is : 113.10 cubic units.

Time Complexity: O(1).

Space Complexity: O(1)

Article Tags :