Open In App

JavaScript Program to Find the Area of Cylinder

Last Updated : 28 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A cylinder is a three-dimensional geometric shape that consists of two parallel bases, which are usually circular, connected by a curved surface. The axis connecting the centers of the two circular bases is the axis of the cylinder. The distance between the centers of the two bases is the height of the cylinder. In this article, we are going to learn the JavaScript Program to Find the Area of Cylinder.

The area (A) of a sphere can be calculated using the given formula:

Area(A) = 2Ï€r(r + h)

Where:

  • r represents the radius of the base of the cylinder.
  • h represents the height of the cylinder.
  • Ï€ represents a mathematical constant approximately equal to 3.14159.

Example:

Input : radius = 5, height = 10
Output: The area of the cylinder is: 471.24
Explanation: Using the formula we get 2*3.14159*5(5+10) = 471.24
Input : radius = 10, height = -10
Output: Error: Radius and height must be non-negative values.
Explanation: As the height is negative which is not possible so it will show an error.

Approach

  • Define a function named calculateCylinderArea that takes the radius and height of a cylinder as arguments.
  • Check if both the radius and height are valid numbers and greater than or equal to 0.
  • If either the radius or height is not a valid number or is negative, return an error message indicating that the values are invalid.
  • If both the radius and height are valid, proceed to calculate the area of the cylinder using the formula 2Ï€r(r+h) and Return the result.

Example: This example shows the implementation of the above-explained approach.

Javascript




// Function to calculate the area of a cylinder
function calculateCylinderArea(radius, height) {
 
    // Check for valid numbers and non-negativity
    if (typeof radius !== 'number' || typeof height
        !== 'number' || radius < 0 || height < 0) {
        return `Error: Invalid input. Radius and
        height must be valid numbers greater
         than or equal to 0.`;
    }
 
    // Formula for the surface area
    // of a cylinder: 2 * Ï€ * r * (r + h)
    const area = 2 * Math.PI * radius * (radius + height);
    return area;
}
 
// Example usage:
const radius = 5;
const height = 10;
 
const cylinderArea =
    calculateCylinderArea(radius, height);
 
if (typeof cylinderArea === "number") {
    console.log(`The area of the cylinder is:
    ${cylinderArea.toFixed(2)}`);
} else {
    console.log(cylinderArea);
}


Output:

The area of the cylinder is: 471.24

Time complexity: O(1), as there are no loops or recursive calls, and the calculations involve basic arithmetic operations.

Auxiliary Space complexity: O(1), as it uses a constant amount of memory regardless of the input size.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads