Introduction
The perimeter of a rectangle is the total distance around the outside of the rectangle. It can be calculated using the formula:
Perimeter=2×(length+width)
This program will help you calculate the perimeter of a rectangle when the length and width are provided.
Problem Statement
Create a JavaScript program that:
- Accepts the length and width of a rectangle.
- Calculates the perimeter of the rectangle.
- Returns and displays the perimeter.
Example:
Input: Length =
5
, Width =10
Output:
30
Input: Length =
7
, Width =4
Output:
22
Solution Steps
- Read the Input Values: Provide the length and width either as user input or directly in the code.
- Calculate the Perimeter: Use the formula
Perimeter = 2 × (length + width)
. - Display the Result: Print the calculated perimeter.
JavaScript Program
// JavaScript Program to Find the Perimeter of a Rectangle
// Author: https://www.javaguides.net/
function calculatePerimeterOfRectangle(length, width) {
// Step 1: Apply the perimeter formula
let perimeter = 2 * (length + width);
// Step 2: Return the result
return perimeter;
}
// Example input
let length = 5;
let width = 10;
let perimeter = calculatePerimeterOfRectangle(length, width);
console.log(`The perimeter of a rectangle with length ${length} and width ${width} is: ${perimeter}`);
Output
The perimeter of a rectangle with length 5 and width 10 is: 30
Example with Different Input
let length = 7;
let width = 4;
let perimeter = calculatePerimeterOfRectangle(length, width);
console.log(`The perimeter of a rectangle with length ${length} and width ${width} is: ${perimeter}`);
Output:
The perimeter of a rectangle with length 7 and width 4 is: 22
Explanation
Step 1: Apply the Perimeter Formula
- The formula for the perimeter of a rectangle is: Perimeter=2×(length+width). This calculates the total distance around the rectangle.
Step 2: Return the Result
- The function returns the calculated perimeter, and the result is printed using
console.log()
.
Conclusion
This JavaScript program demonstrates how to calculate the perimeter of a rectangle using its length and width. The formula is simple, and the program efficiently computes and displays the result. This method can be applied to handle perimeter calculations for different rectangle dimensions in real-world scenarios.
Comments
Post a Comment
Leave Comment