Q:

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

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now