Q:

Write a Scala program to sum values of an given array

0

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

All Answers

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

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

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