w3resource

Scala Programming: Create a new array taking the middle element from three arrays of length 5

Scala Programming Array Exercise-11 with Solution

Write a Scala program to create a new array taking the middle element from three arrays of length 5.

Sample Solution:

Scala Code:

object Scala_Array {   
   def test(x: Array[Int], y: Array[Int], z: Array[Int]): Array[Int] = {
    if (x.length != 5 || y.length != 5 || z.length != 5) throw new IllegalArgumentException("Array length not matched!")  
    else Array(x(2), y(2), z(2))
  }     
   def main(args: Array[String]): Unit = {
      var result1 = test(Array(1,2,3,4,5),Array(2,3,4,5,6),Array(3,4,5,6,7))
     // Print all the array elements
      println("New array:")
        for ( x <- result1 ) {
          print(s"${x}, ")        
          }
      } 
 }

Sample Output:

New array:
3, 4, 5,

Scala Code Editor :

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

Previous: 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.
Next: Write a Scala program to reverse an array of integer values.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.