JavaScript Program to Find Radius if Diameter is Given
Given the diameter, our task is to find the radius of the circle in JavaScript. The radius of a circle is the distance from the center of the circle to any point on its circumference. The diameter of a circle represents the distance from one side of the circle, passing through its center, to the opposite side.
Example:
Formula for calculating radius is :
r = d/2
Where,
d is the diameter of a circle
r is the radius of a circle
Below are the approaches to finding the radius if the diameter is given in JavaScript:
Table of Content
- Using Function
- Using Class
Using Function
In this approach, the code defines a function, findRadius, that takes the diameter of the Circle as an input parameter for calculating the radius of circle. It then invokes the function with a diameter value of 8. Inside the function, use the formula: d/2, to calculate the radius of the circle. Finally, return the result.
Example: The example below shows the demonstration of finding the radius of the circle using a function.
function findRadius(diameter) {
return diameter / 2;
}
const diameter = 8;
const radius = findRadius(diameter);
console.log("Radius of the circle is:", radius);
Output
Radius of the circle is: 4
Time Complexity: O(1)
Space Complexity: O(1)
Using Class
In this approach, we define a class named Circle. Inside the class, define a constructor method that takes a parameter diameter to represent the diameter of the Circle. Within the constructor, calculate the radius of the Circle using the formula: d/2. After creating an instance of the Circle class with the desired diameter passed as an argument to the constructor, call the method we created to calculate the radius and print the result.
Example: The example below shows the demonstration of finding radius of circle using class.
class Circle {
constructor(diameter) {
this.diameter = diameter;
}
findRadius() {
return this.diameter / 2;
}
}
const circle = new Circle(8);
const radius = circle.findRadius();
console.log("Radius of the circle is:", radius);
Output
Radius of the circle is: 4
Time Complexity: O(1)
Space Complexity: O(1)