Q:

Write a Scala program to find the maximum and minimum value of an array of integers

0

Write a Scala program to find the maximum and minimum value of an array of integers.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now