Scala program to find the sum of array elements using a for loop
Scala Control Flow Exercise-7 with Solution
Write a Scala program to find the sum of all elements in an array using a for loop.
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?
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/control-flow/scala-control-flow-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics