How to find the Maximum of an array of numbers?

·

2 min read

If an array of numbers is given how we can find its maximum element?
We will answer this question in this article, firstly by examine a simple example and then by creating a function that accepts an array of numbers as input and outputs the maximum element of the array.
We will use JavaScript, but the same logic can be applied in any programming language.

Example: If is given to us the array a = [3, 1, 2, 5, 7], how we can find it's maximum element?
We will use a temporary variable:

let a = [3, 1, 2, 5, 7]
let max = a[0]  // temporary variable

// we iterate through a and we compare max with each element
// if the element is greater than max, then we assign the value of the element 
// to the max variable
for (let i = 0; i < a.length; i++) {
  if (max < a[i]) {
    max = a[i]    
  }
}
// max === 7

Now the max variable contains the maximum element of array a. That's because if there was a greater element in the array a than max (after the loop runs), then it's value should have been inserted to the max variable, when the comparison with the current max value took palce (or earlier).

Now lets create the function we mentioned in the beggining of the article:

let a = [3, 1, 2, 5, 7]

function maximum(arr) {
  let max = arr[0] // temporary variable
  for (let i = 0; i <arr.length; i++) {
    if (max < arr[i]) {
      max = arr[i]    
    }
  }
  return max
}

console.log(maximum(a)); // 7

Exercise: Write a function that accepts an array of numbers as input and outputs it's minimum number. The logic of your solution must be applicable in any progrmming language.

Did you find this article valuable?

Support Dimitris's blog by becoming a sponsor. Any amount is appreciated!