w3resource

Scala Program: Calculating the average of elements in a set

Scala Set Exercise-16 with Solution

Write a Scala program to create a set and find the average of all elements in the set.

Sample Solution:

Scala Code:

object AverageOfElementsSetExample {
  def main(args: Array[String]): Unit = {
    // Create a set
    val nums = Set(10, 20, 30, 40, 50)

    // Print the set
    println("Set: " + nums)

    // Find the average of all elements in the set
    val average = nums.sum.toDouble / nums.size

    // Print the average
    println("Average of elements: " + average)
  }
}

Sample Output:

Set: HashSet(10, 20, 50, 40, 30)
Average of elements: 30.0

Explanation:

In the above exercise,

  • First, we create a set "nums" with the elements 10, 20, 30, 40, and 50.
  • To find the average of all elements in the set, we calculate the sum of all elements using the sum method and divide it by the size of the set using the size method. We convert the sum to Double to ensure the division is a floating-point division.
  • In the program, we find the average of all elements in the set by using the line val average = set.sum.toDouble / set.size.
  • Finally, we print the set and the average of all elements.

Scala Code Editor :

Previous: Calculating the sum of elements in a set.
Next: Find the second largest element in a set.

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://www.w3resource.com/scala-exercises/sets/scala-set-exercise-16.php