TypeScript: Find the Maximum Element in an Array

1. Introduction

Finding the maximum element in an array is a fundamental operation in computer science. It's a straightforward process but can be optimized in various ways depending on the context. Today, we'll look into a simple TypeScript program to retrieve the largest number from an array.

2. Program Overview

We will be defining a function named findMax which will take an array of numbers and return the highest value from that array. We'll utilize TypeScript's type definition for added clarity and robustness.

3. Code Program

// Function to find the maximum element in an array
function findMax(numbers: number[]): number {
    let maxNumber = numbers[0]; // Assume the first number is the maximum
    for (let num of numbers) {
        if (num > maxNumber) {
            maxNumber = num; // Update the maxNumber if current number is greater
        }
    }
    return maxNumber; // Return the maximum number
}

// Testing the function
const numbers = [5, 2, 9, 1, 5, 6];
console.log(`The array is: [${numbers}]`);
console.log(`The maximum number is: ${findMax(numbers)}`);

Output:

The array is: [5, 2, 9, 1, 5, 6]
The maximum number is: 9

4. Step By Step Explanation

1. We start by defining our findMax function that accepts an array named numbers.

2. Inside the function, we initialize a variable maxNumber with the value of the first element of the array. This acts as our initial assumption for the maximum value.

3. We then loop over the numbers array using a for-of loop. For each num in numbers, we compare it against the current maxNumber.

4. If num is greater than maxNumber, we update maxNumber with the value of num.

5. After looping through all the numbers, we compare each number in the array to our current maximum and update it as necessary. Hence, by the end of the loop, maxNumber holds the maximum value from the array.

6. Finally, we return the maxNumber.

7. We then test our function with a sample array of numbers and display both the array and its maximum number.

Comments