Open In App

JavaScript Program to Find Area of semi-circle

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

Given the radius, our task is to find an area of a semi-circle in JavaScript. A semi-circle is a two-dimensional geometric shape that represents half of a circle. The area of a semi-circle can be calculated by squaring the radius of the semi-circle, then multiplying it by π and dividing by 2.

Example:

Formula for calculating area of semi-Circle is : (π × r2)/2 
Where, r is radius of a circle
 π is constant having value 3.1415926535

Table of Content

Using Function

In this approach, the code defines a function, AreaOfSemiCircle, that takes the radius of the semi-circle as an input parameter for calculating the area of a semi-circle. It then invokes the function with a radius value of 7. Inside the function, use the formula : (π × r2)/2 to calculate area of semi-circle. Finally return the result.

Example: The example below shows the demonstration of finding area of semi-circle using function.

JavaScript
function AreaOfSemiCircle(radius) {
    return (Math.PI * radius * radius) / 2;
}
const radius = 7;
const area = AreaOfSemiCircle(radius);
console.log("Area of semi-circle is :",
                    area.toFixed(2));

Output
Area of semi-circle is : 76.97

Time Complexity: O(1)

Space Complexity: O(1)

Using Class

In this approach, we define a class named SemiCircle. Inside the class, define a constructor method that takes a parameter radius to represent the radius of the semi-circle. Within the constructor, calculate the area of the semi-circle using the formula π × r^2)/2. After creating an instance of the SemiCircle class with the desired radius passed as an argument to the constructor, call the method we created to calculate the area and print the result.

Example: The example below shows the demonstration of finding area of semi-circle using class.

JavaScript
class SemiCircle {
    constructor(radius) {
        this.radius = radius;
    }
    getArea() {
        return (Math.PI * this.radius 
                        * this.radius) / 2;
    }
}
const semiCircle = new SemiCircle(6);
const area = semiCircle.getArea(); 
console.log("Area of semi-circle is:",
                area.toFixed(2));

Output
Area of semi-circle is: 56.55

Time Complexity: O(1)

Space Complexity: O(1)


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

Similar Reads