JavaScript program to find perimeter of a triangle


We will find the perimeter of a triangle by adding the lengths of its three sides. To do this, we will first declare three variables to store the lengths of the sides and then use the addition operator to sum these values and store the result in a fourth variable. Finally, we will print out the value stored in the fourth variable to get the perimeter of the triangle.

Approach

Here is a JavaScript program to find the perimeter of a triangle −

function trianglePerimeter(a, b, c) {
   return a + b + c;
}

Explanation

  • A function named trianglePerimeter is defined which takes three arguments a, b, and c.

  • The function returns the sum of the three arguments, which represents the perimeter of the triangle.

  • The three arguments represent the length of the sides of the triangle.

  • The function simply adds up the lengths of the sides to find the total length, which is the perimeter.

  • To use this function, pass in the lengths of the sides of the triangle as arguments.

  • The result returned by the function will be the perimeter of the triangle.

Example

Here is an example of a JavaScript program to find the perimeter of a triangle −

function trianglePerimeter(a, b, c) {
   return a + b + c;
}
let side1 = 3;
let side2 = 4;
let side3 = 5;
let perimeter = trianglePerimeter(side1, side2, side3);
console.log(`The perimeter of the triangle is ${perimeter}.`);

Explanation

  • trianglePerimeter is a function that takes in three parameters, a, b, and c, representing the lengths of the sides of the triangle.

  • The function returns the sum of these three sides, which is the perimeter of the triangle.

  • The variables side1, side2, and side3 are assigned the values of the three sides of the triangle.

  • The perimeter of the triangle is calculated by calling the trianglePerimeter function and passing in the values of side1, side2, and side3 as arguments.

  • The perimeter is logged to the console using console.log and a template literal.

Updated on: 15-Mar-2023

361 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements