Q:

Write a Scala program to calculate the average value of an array of element

0

Write a Scala program to calculate the average value of an array of element.

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, 3, 4, 5, 6)
     println("Original Array elements:")
     // Print all the array elements
      for ( x <- nums ) {
         print(s"${x}, ")        
       }
     //Sum using for loop
     var total = 0.0;      
      for ( i <- 0 to (nums.length - 1)) {
         total += nums(i);
      }
      println(s"\nAverage value of the array elements is: ${total/nums.length}");
   }
}

Sample Output:

Original Array elements:
1, 2, 3, 4, 5, 6, 
Average value of the array elements is: 3.5

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