w3resource

Scala program to find the sum of array elements using a for loop


Write a Scala program to find the sum of all elements in an array using a for loop.


Pre-Knowledge (Before you start!)

  • Basic Scala Syntax: Familiarity with writing and running Scala programs.
  • Arrays in Scala: Knowledge of creating and working with arrays, including iterating through elements.
  • For Loops: Understanding how to use for loops to iterate over array elements.
  • Variable Initialization: Ability to initialize and update variables during program execution.
  • Arithmetic Operations: Awareness of performing addition to calculate the sum of numbers.
  • Printing Output: Familiarity with the print() and println() functions to display output on the screen.

Hints (Try before looking at the solution!)

  • Define the Main Object: Create an object with a main method, which serves as the entry point of the program.
  • Initialize the Array: Declare and initialize an array containing the numbers whose sum you want to calculate.
  • Initialize a Sum Variable: Start with a variable initialized to 0 to store the cumulative sum of the array elements.
  • Use a For Loop: Use a for loop to iterate through each element of the array. Add each element to the sum variable during each iteration.
  • Display the Array Elements: Use another for loop to print all the elements of the array in a readable format.
  • Display the Sum: Use println() to print the total sum of the array elements in a clear and formatted manner.
  • Test with Different Arrays: Change the array values to verify the program works for various cases, including empty arrays or arrays with negative numbers.
  • Common Errors to Avoid:
    • Forgetting to initialize the sum variable correctly, leading to incorrect results.
    • Misplacing the addition logic inside the loop, causing incomplete or incorrect calculations.
    • Not handling edge cases like empty arrays, which may lead to unexpected behavior.

Sample Solution:

Scala Code:

object ArraySum {
  def main(args: Array[String]): Unit = {
    val numbers: Array[Int] = Array(1, 2, 3, 4, 5, 6) //Array containing the numbers

    var sum: Int = 0
    for (number <- numbers) {
      sum += number
    }
    println("Original Array elements:")
     // Print all the array elements
      for ( x <- numbers ) {
         print(s"${x}, ")        
       }
    println(s"\nThe sum of the array elements is: $sum")
  }
}

Sample Output:

Original Array elements:
1, 2, 3, 4, 5, 6, 
The sum of the array elements is: 21

Explanation:

In the above exercise,

  • First we define an array "numbers" and initialize it with a sequence of numbers (1, 2, 3, 4, 5, 6 in this case). This array represents the numbers for which we want to calculate the sum.
  • We initialize a variable sum to 0, which stores the sum of the array elements. Using a for loop, we iterate over each element number in the "numbers" array. Inside the loop, we add the current number to the sum variable.
  • After the loop finishes, we print the result using println, which displays the sum of all elements in the array.

Scala Code Editor :

Previous: Multiplication table using a for loop.
Next: Check Palindrome using if/else and pattern matching.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.