TypeScript: Find the Maximum of Three Numbers

1. Introduction

Comparing numbers to determine the largest or smallest is a fundamental operation in programming. In this guide, we will write a TypeScript function that finds the maximum number among three given numbers.

2. Program Overview

We will implement a function named findMaximum. This function will accept three numbers as parameters. Through a series of comparisons, it will determine and return the largest number.

3. Code Program

// Function to find the maximum of three numbers
function findMaximum(num1: number, num2: number, num3: number): number {
    // Assuming num1 is the maximum initially
    let max: number = num1;

    // Compare num2 with max
    if(num2 > max) {
        max = num2;
    }

    // Compare num3 with max
    if(num3 > max) {
        max = num3;
    }

    // Return the maximum number
    return max;
}

// Testing the function
const a: number = 10;
const b: number = 25;
const c: number = 15;
console.log(`The maximum of ${a}, ${b}, and ${c} is: ${findMaximum(a, b, c)}`);

Output:

The maximum of 10, 25, and 15 is: 25

4. Step By Step Explanation

1. We start by defining a function findMaximum that accepts three numbers.

2. Initially, we assume that the first number, num1, is the largest.

3. We then compare the second number, num2, with our current maximum. If num2 is larger, we update our max variable.

4. Similarly, we compare the third number, num3, with our current maximum. If num3 is larger, we update our max variable.

5. After comparing all numbers, our max variable holds the largest number which we return.

6. In our test, for the numbers 10, 25, and 15, the function correctly identifies 25 as the largest number and outputs it.

Comments