Q:

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

0

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.

All Answers

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

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

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