JavaScript Program to Find the Area of a Circle

Introduction

The area of a circle is a measure of the space inside the circle, and it can be calculated using the formula:

Area=Ï€×r2

Where r is the radius of the circle and π (pi) is approximately 3.14159. This program helps calculate the area of a circle based on the radius provided.

Problem Statement

Create a JavaScript program that:

  • Accepts the radius of a circle.
  • Calculates the area of the circle.
  • Returns and displays the area.

Example:

  • Input: 5 (radius)

  • Output: 78.54 (area)

  • Input: 7 (radius)

  • Output: 153.94 (area)

Solution Steps

  1. Read the Input: Provide the radius of the circle either as user input or directly within the code.
  2. Calculate the Area: Use the formula Area = Ï€ × r².
  3. Display the Result: Print the calculated area.

JavaScript Program

// JavaScript Program to Find the Area of a Circle
// Author: https://www.javaguides.net/

function calculateAreaOfCircle(radius) {
    // Step 1: Apply the area formula (Ï€ × r²)
    let area = Math.PI * Math.pow(radius, 2);

    // Step 2: Return the result
    return area;
}

// Example input
let radius = 5;
let area = calculateAreaOfCircle(radius);
console.log(`The area of a circle with radius ${radius} is: ${area.toFixed(2)}`);

Output

The area of a circle with radius 5 is: 78.54

Example with Different Input

let radius = 7;
let area = calculateAreaOfCircle(radius);
console.log(`The area of a circle with radius ${radius} is: ${area.toFixed(2)}`);

Output:

The area of a circle with radius 7 is: 153.94

Explanation

Step 1: Apply the Area Formula

  • The area of the circle is calculated using the formula: Area=Ï€×r2. In the program, Math.PI provides the value of Ï€, and Math.pow(radius, 2) calculates the square of the radius.

Step 2: Return the Result

  • The function returns the calculated area, and the result is printed using console.log(). The output is rounded to two decimal places using toFixed(2).

Conclusion

This JavaScript program demonstrates how to calculate the area of a circle using the radius and the formula for area. By leveraging JavaScript's built-in Math library, this program provides an easy and efficient way to handle geometric calculations such as finding the area of a circle.

Comments