Scala program to find the sum and average of elements in an array

1. Introduction

Finding the sum and average of elements in an array is a fundamental operation that showcases the essence of aggregation in programming. Scala, being a functional and object-oriented language, provides intuitive methods to perform such operations on arrays efficiently.

2. Program Steps

1. Set up the Scala environment.

2. Initialize the array of numbers.

3. Calculate the sum of the elements in the array.

4. Determine the average of the elements.

5. Display the calculated sum and average.

6. Execute the program.

3. Code Program

object ArrayOperationsApp {
  def main(args: Array[String]): Unit = {
    // Sample array
    val numbers = Array(10, 20, 30, 40, 50)

    // Calculate sum and average
    val totalSum = sumOfElements(numbers)
    val average = averageOfElements(numbers, totalSum)

    println(s"Array: ${numbers.mkString("[", ", ", "]")}")
    println(s"Sum: $totalSum")
    println(s"Average: $average")
  }

  def sumOfElements(arr: Array[Int]): Int = {
    arr.sum
  }

  def averageOfElements(arr: Array[Int], total: Int): Double = {
    total.toDouble / arr.length
  }
}

Output:

Array: [10, 20, 30, 40, 50]
Sum: 150
Average: 30.0

Explanation:

1. ArrayOperationsApp object is the container for our program logic.

2. Within the main function, we have defined a sample numbers array.

3. The sumOfElements function accepts an array and returns the sum of its elements. It uses the built-in sum method of Scala's Array class.

4. The averageOfElements function takes in the array and its total sum to compute the average. The sum is divided by the length of the array to determine the average value.

5. Both the sum and average values are printed to the console.


Comments