w3resource

Scala Programming: Get the difference between the largest and smallest values in an array of integers

Scala Programming Array Exercise-24 with Solution

Write a Scala program to get the difference between the largest and smallest values in an array of integers. The length of the array must be 1 and above.

Sample Solution:

Scala Code:

object scala_basic {
  def main(args: Array[String]): Unit = {
    var array_nums = Array(5, 7, 2, 4, 9);
    if (array_nums.length > 1) {
      println("Original array:")
      for (x <- array_nums) {
        print(s"${x}, ")
      }
      var max_val = array_nums(0);
      var min = array_nums(0);
      for (i <- 0 to array_nums.length - 1) {
        if (array_nums(i) > max_val)
          max_val = array_nums(i);
        else if (array_nums(i) < min)
          min = array_nums(i);
      }

      println(
        s"\nDifference between the largest and smallest values of the said array is: ${max_val - min}"
      )
    }
  }
}

Sample Output:

Original array:
5, 7, 2, 4, 9, 
Difference between the largest and smallest values of the said array is: 7

Scala Code Editor :

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

Previous: Write a Scala program to find the number of even and odd integers in a given array of integers.

Next: Write a Scala program to compute the average value of an array element except the largest and smallest values.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://w3resource.com/scala-exercises/array/scala-array-exercise-24.php