Open In App

JavaScript Program to Find the Area of Sphere

A sphere is a three-dimensional geometric shape that is perfectly round and symmetrical in all directions. It is defined as the set of all points in space that are equidistant (at an equal distance) from a central point. This central point is called the center of the sphere. In this article, we are going to learn how to find the area of the Sphere.



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

Area(A) = 4 * π * r2



where,

Example:

Input : radius = 5
Output: Area of the sphere: 314.16
Explanation: Using the formula we get 4*3.1416*5*5 = 314.16


Input : radius = -10
Output: Error: Invalid radius. Please enter a valid positive number.
Explanation: As the radius is negative which is not possible so it will show an error.

Approach:

Example: Below is the function to find area of Sphere:




// Function to calculate the area of a sphere
function calculateSphereArea(radius) {
 
    // Check if the radius is a valid number
    if (isNaN(radius) || radius < 0) {
        return "Error: Invalid radius. Please enter a valid positive number.";
    }
 
    // Calculate the area of the sphere
    let area = 4 * Math.PI * Math.pow(radius, 2);
 
    return area;
}
 
// Example usage
// You can change this to any value, including invalid ones
let radius = 5;
let sphereArea = calculateSphereArea(radius);
 
// Check if the result is a number before displaying
if (typeof sphereArea === 'number') {
 
    // toFixed(2) for two decimal places
    console.log("Area of the sphere: " + sphereArea.toFixed(2));
} else {
 
    // Display the error message
    console.log(sphereArea);
}

Output
Area of the sphere: 314.16

Time complexity: O(1), as the execution time is constant and does not grow with the size of the input.

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


Article Tags :