w3resource

Scala Programming: Calculate the sum of the last 3 elements of an array of integers

Scala Programming Array Exercise-10 with Solution

Write a Scala program to calculate the sum of the last 3 elements of an array of integers. If the array length is less than 3 then return the sum of the array. Return 0 if the array is empty.

Sample Solution:

Scala Code:

object Scala_Array {

  def sum_last_3(arr: Array[Int]): Int = {
     if (arr.length < 1) 0 
     else if (arr.length > 0  && arr.length < 3) arr.takeRight(2).sum
     else arr.takeRight(3).sum
  }
     
   def main(args: Array[String]): Unit = {
        val nums1 = Array(1, 2, 3, 4, 5, 7, 9, 11, 14, 12, 16)        
        println("Original Array elements:")
        // Print all the array elements
        for ( x <- nums1 ) {
         print(s"${x}, ")        
          }
      println("\nSum of the last 3 elements of the said array: "+sum_last_3(nums1))
      
       val nums2 = Array(12, 16)        
        println("Original Array elements:")
        // Print all the array elements
        for ( x <- nums2 ) {
         print(s"${x}, ")        
          }
         println("\nSum of the last 2 elements of the said array: "+sum_last_3(nums2))   
     
        var nums4 : Array[Int] = Array()
        println("\nSum of the blank array: "+sum_last_3(nums4))   

      } 
 }

Sample Output:

Original Array elements:
1, 2, 3, 4, 5, 7, 9, 11, 14, 12, 16, 
Sum of the last 3 elements of the said array: 42
Original Array elements:
12, 16, 
Sum of the last 2 elements of the said array: 28
Sum of the blank array: 0

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to find the maximum and minimum value of an array of integers.
Next: Write a Scala program to create a new array taking the middle element from three arrays of length 5.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/array/scala-array-exercise-10.php