Scala Programming: Calculate the average value of an array of elements
Scala Programming Array Exercise-3 with Solution
Write a Scala program to calculate the average value of an array of element.
Sample Solution:
Scala Code:
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
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: 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.
Next: Write a Scala program to check if the value of the fast or last element of a given array ( length 1 or more) are same or not.
What is the difficulty level of this exercise?
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-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics