Open In App

Program to Find Volume of Cone using JavaScript

Last Updated : 22 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We will learn how to find the volume of a cone using JavaScript. A cone is a three-dimensional geometric shape with a circular base and a pointed top. We will use the formula to return the volume of a cone.

Formula Used

volume of a cone is:  (1/3) × π × r

where:

  • r is the radius of the base of the cone.
  • h is the height of the cone.
  • Ï€ is the mathematical constant whose value is equal to 3.14.

Using Function

Create a function that takes the radius and height of the cone as input parameters. Inside the function, we will calculate volume of cone using the formula for volume of cone : (1/3) × π × r2 × h. Call the function and return the calculated volume of cone.

Example: To demonstrate finding Volume of Cone using function.

JavaScript
// Using function

function coneVolume(radius, height) {
    const pi = Math.PI;
    return (1 / 3) * pi * Math.pow(radius, 2) * height;
}
const radius = 4; 
const height = 12; 

const volume = coneVolume(radius, height);
console.log("Volume of the cone is:", volume);

Output
Volume of the cone is: 201.06192982974676

Time Complexity: O(1)

Space Complexity: O(1)

Using Class

We will define a class named Cone with a constructor method to initialize the radius and height of the cone, and we will define a method to calculate the volume of cone using the formula : (1/3) × π × r2 × h. Then we create an instance of the Cone class, pass the radius and height as arguments to the constructor. Call the method and print the result.

Example: The example below shows the demonstration of finding volume of cone using class.

JavaScript
// Using class

class Cone {
    constructor(radius, height) {
        this.radius = radius;
        this.height = height;
    }

    calculateVolume() {
        const pi = Math.PI;
        return (1 / 3) * pi * Math.pow(this.radius, 2)
                       * this.height;
    }
}


const cone = new Cone(4, 12); 
const volume = cone.calculateVolume();
console.log("Volume of the cone :", volume);

Output
Volume of the cone : 201.06192982974676

Time Complexity: O(1)

Space Complexity: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads