w3resource

Scala Program: Calculating the sum of elements in a set

Scala Set Exercise-15 with Solution

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

Sample Solution:

Scala Code:

object SumOfElementsSetExample {
  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 sum of all elements in the set
    val sum = nums.sum

    // Print the sum
    println("Sum of elements: " + sum)
  }
}

Sample Output:

Set: HashSet(10, 20, 50, 40, 30)
Sum of elements: 150

Explanation:

In the above exercise,

  • First, we create a set "nums" with the elements 10, 20, 30, 40, and 50.
  • To find the sum of all elements in the set, we use the sum method, which returns the sum of all elements in the set.
  • In the program, we find the sum of all elements in the set by using the line val sum = set.sum.
  • Finally, we print the set and the sum of all elements.

Scala Code Editor :

Previous: Find the minimum element in a set.
Next: Calculating the average of elements 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-15.php