w3resource

Scala Programming: Average value of an array element except the largest and smallest values

Scala Programming Array Exercise-25 with Solution

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

Sample Solution:

Scala Code:

object scala_basic {
  def main(args: Array[String]): Unit = {
  var array_nums = Array(5, 7, 2, 4, 9);
  println("Original array:")
   for (x <- array_nums) {
      print(s"${x}, ")
    }
	var max = array_nums(0)
	var min = array_nums(0)
	var sum: Double = 0
	for (i <- 0 to array_nums.length - 1)
	{
		sum = sum + array_nums(i);
		if(array_nums(i) > max)
			max = array_nums(i);
		else if(array_nums(i) < min)
			min = array_nums(i);
	}
	val x: Double = ((sum-max-min) / (array_nums.length - 2));
	println(s"\nAverage value the said array elements except the largest and smallest values: ${x}");
	}
}

Sample Output:

Original array:
5, 7, 2, 4, 9, 
Average value the said array elements except the largest and smallest values: 5.333333333333333

Scala Code Editor :

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

Previous: 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.
Next: Write a Scala program to remove the duplicate elements of a given sorted array and return the new length of the array.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.