w3resource

Scala function: Find the maximum element

Scala Function Exercise-6 with Solution

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

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.