TypeScript: Calculate the Area of a Triangle

1. Introduction

In geometry, the area of a triangle is calculated using the formula 0.5 * base * height, where base is the length of the base of the triangle and height is the perpendicular distance from the base to the opposite vertex. In this post, we will develop a TypeScript function to determine the area of a triangle given its base and height.

2. Program Overview

Our aim is to implement a function named calculateTriangleArea that will accept the base and height of the triangle as parameters. The function will compute and return the area of the triangle using the formula provided.

3. Code Program

// Function to calculate the area of a triangle given its base and height
function calculateTriangleArea(base: number, height: number): number {
    return 0.5 * base * height;
}

// Testing the function
const triangleBase: number = 10;
const triangleHeight: number = 5;
console.log(`The area of a triangle with base ${triangleBase} and height ${triangleHeight} is: ${calculateTriangleArea(triangleBase, triangleHeight)}`);

Output:

The area of a triangle with base 10 and height 5 is: 25

4. Step By Step Explanation

1. We begin by defining a function named calculateTriangleArea. This function takes two parameters: the base and the height of a triangle.

2. Inside the function, we use the formula 0.5 base * height to calculate the area of the triangle.

3. We then return the computed area from the function.

4. For demonstration, we set the base of the triangle to 10 units and the height to 5 units.

5. Upon invoking the function with these values, it computes the area as 25 square units and outputs the result.

Comments