Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Scala Programming: Find the maximum value from first, middle and last values of a given array of integers

Scala Programming Array Exercise-14 with Solution

Write a Scala program to find the maximum value from first, middle and last values of a given array of integers. Array length should be 1 and more and odd.

Sample Solution:

Scala Code:

object Scala_Array {   
   def test(nums: Array[Int]): Int = {
    if (nums.length == 1) nums(0)
    Array(nums(0), nums(nums.length / 2), nums(nums.length - 1)).max
  }
   def main(args: Array[String]): Unit = {     
    var nums1 = Array(2,14,5,7,9) 
    println("Orginal array:")
    for ( x <- nums1) {
       print(s"${x}, ")        
     }           
    println("\nMaximum value from first, middle and last values: "+test(nums1))    
    var nums2 = Array(22,5,5,6,1) 
    println("Orginal array:")
    for ( x <- nums2) {
       print(s"${x}, ")        
     }          
    println("\nMaximum value from first, middle and last values: "+test(nums2))
    var nums3 = Array(2,5,17,6,9) 
    println("Orginal array:")
    for ( x <- nums3) {
       print(s"${x}, ")        
     }           
    println("\nMaximum value from first, middle and last values: "+test(nums3))
    
  }
}

Sample Output:

Orginal array:
2, 14, 5, 7, 9, 
Maximum value from first, middle and last values: 9
Orginal array:
22, 5, 5, 6, 1, 
Maximum value from first, middle and last values: 22
Orginal array:
2, 5, 17, 6, 9, 
Maximum value from first, middle and last values: 17

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to check two numbers, 4 or 7 present in a given array of integers.
Next: Write a Scala program to find the common elements between two arrays of integers.

What is the difficulty level of this exercise?