Iterate over a list and calculate sum and product
Scala Programming List Exercise-5 with Solution
Write a Scala program to iterate over a list to print the elements and calculate the sum and product of all elements of this list.
Sample Solution:
Scala Code:
object Scala_List
{
def main(args: Array[String]): Unit =
{
//Iterate over a list
val nums = List(1, 3, 5, 7, 9)
println("Iterate over a list:")
for( i <- nums)
{
println(i)
}
println("Sum all the items of the said list:")
//Applying sum method
val result = nums.sum
println(result)
println("Multiplies all the items of the said list:")
val result1 = nums.product
println(result1)
}
}
Sample Output:
Iterate over a list: 1 3 5 7 9 Sum all the items of the said list: 25 Multiplies all the items of the said list: 945
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Scala program to delete element(s) from a given List.
Next: Write a Scala program to find the largest and smallest number from a given list.
What is the difficulty level of this exercise?
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework