Scala Programming: Find the maximum and minimum value of an array of integers
Scala Programming Array Exercise-9 with Solution
Write a Scala program to find the maximum and minimum value of an array of integers.
Sample Solution:
Scala Code:
object Scala_Array {
def min_max(a: Array[Int]) : (Int, Int) = {
if (a.isEmpty) throw new IllegalArgumentException("Blank Array...!")
a.foldLeft((a(0), a(0)))
{ case ((min, max), e) => (math.min(min, e), math.max(max, e))}
}
def main(args: Array[String]): Unit = {
val nums1 = Array(1, 2, 3, 4, 5, 7, 9, 11, 14, 12, 16)
println("Original Array elements:")
// Print all the array elements
for ( x <- nums1 ) {
print(s"${x}, ")
}
println("\nMaximum - Minimum value of the said array: " +min_max(nums1));
val nums2 = Array(-111,-124)
println("Original Array elements:")
// Print all the array elements
for ( x <- nums2 ) {
print(s"${x}, ")
}
println("\nMaximum - Minimum value of the said array: " +min_max(nums2));
val nums3 = Array(10)
println("Original Array elements:")
// Print all the array elements
for ( x <- nums3 ) {
print(s"${x}, ")
}
println("\nMaximum - Minimum value of the said array: " +min_max(nums3));
var nums4 : Array[Int] = Array()
println("Result: " +min_max(nums4));
}
}
Sample Output:
Original Array elements: 1, 2, 3, 4, 5, 7, 9, 11, 14, 12, 16, Maximum - Minimum value of the said array: (1,16) Original Array elements: -111, -124, Maximum - Minimum value of the said array: (-124,-111) Original Array elements: 10, Maximum - Minimum value of the said array: (10,10)
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Scala program to rotate one element left of an given array (length 1 or more) of integers.
Next: Write a Scala program to calculate the sum of the last 3 elements of an array of integers. If the array length is less than 3 then return the sum of the array. Return 0 if the array is empty.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/scala-exercises/array/scala-array-exercise-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics