w3resource

Scala Programming: Sum values of an given array

Scala Programming Array Exercise-1 with Solution

Write a Scala program to sum values of an given array.

Sample Solution:

Scala Code:

object Scala_Array {   
   def main(args: Array[String]): Unit = {
     var nums = Array(1.2, 1.7, 1.12, 1.16, 1.81, 1.99)
     println("Original Array elements:")
     // Print all the array elements
      for ( x <- nums ) {
         print(s"${x}, ")        
       }
     println("\nUsing sum():")
     val result = nums.sum
     println(s"Result: ${result}");   
     println("\nUsing for loop:")
     var total = 0.0;      
      for ( i <- 0 to (nums.length - 1)) {
         total += nums(i);
      }
      println(s"Result: ${total}");
   }
}

Sample Output:

Original Array elements:
1.2, 1.7, 1.12, 1.16, 1.81, 1.99, 
Using sum():
Result: 8.98
Using for loop:
Result: 8.98

Scala Code Editor :

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

Previous: Scala Programming Array Exercises Home.
Next: Write a Scala program to check if a given number is present in fast or last position of a given array of length 1 or more.

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-1.php