Open In App

JavaScript Program to Find the Area of Cylinder

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:



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

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




// 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.


Article Tags :