w3resource

Scala function: Find the maximum element


Write a Scala function to find the maximum element in an array.


Before you start!

To solve this problem, you should have a basic understanding of:

  • Scala arrays and how to declare them.
  • Looping through an array using a for loop.
  • Comparison operations to find the largest element.
  • Handling edge cases, such as an empty array.

Try before looking at the solution!

Think about how you can find the maximum element in an array:

  • How can you iterate through each element of the array?
  • How do you compare elements to find the maximum?
  • What variable should you use to store the maximum value?
  • How do you handle an empty array to avoid errors?

Sample Solution:

Scala Code:

object ArrayMaxElementFinder {
  def findMaxElement(arr: Array[Int]): Int = {
    if (arr.isEmpty) {
      throw new IllegalArgumentException("Array is empty")
    }
    
    var maxElement = arr(0)
    for (i <- 1 until arr.length) {
      if (arr(i) > maxElement) {
        maxElement = arr(i)
      }
    }
    
    maxElement
  }

  def main(args: Array[String]): Unit = {
    val nums = Array(5, 2, 9, 1, 7, 9, 0)
    println("Original Array elements:")
     // Print all the array elements
      for ( x <- nums ) {
         print(s"${x}, ")        
       }
    val maxElement = findMaxElement(nums)
    println(s"\nThe maximum element in the array is: $maxElement")
  }
}

Sample Output:

Original Array elements:
5, 2, 9, 1, 7, 9, 0, 
The maximum element in the array is: 9

Scala Code Editor :

Previous: Check if a string is a palindrome.
Next: Calculate the Power of a Number.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.