Scala program to merge two arrays

1. Introduction

In many scenarios, we might need to combine two arrays into one. This operation, often referred to as "merging", is a fundamental operation in programming. Scala, with its rich library, offers a straightforward approach to merge two arrays. Let's see how we can achieve this.

2. Program Steps

1. Set up the Scala environment.

2. Declare two arrays with sample values.

3. Use the ++ operator to merge the two arrays.

4. Display the merged array.

5. Run the program.

3. Code Program

object MergeArraysApp {
  def main(args: Array[String]): Unit = {
    // Two sample arrays
    val array1 = Array(1, 2, 3)
    val array2 = Array(4, 5, 6)

    // Merging arrays using the ++ operator
    val mergedArray = mergeArrays(array1, array2)

    println(s"Merged array: ${mergedArray.mkString("[", ", ", "]")}")
  }

  def mergeArrays(arr1: Array[Int], arr2: Array[Int]): Array[Int] = {
    arr1 ++ arr2
  }
}

Output:

Merged array: [1, 2, 3, 4, 5, 6]

Explanation:

1. The MergeArraysApp object is created to encapsulate our main program.

2. Within the main function, we declare two arrays, array1 and array2, with sample values.

3. The mergeArrays function is responsible for merging the arrays. It uses the ++ operator, which is an intuitive way in Scala to concatenate or merge arrays.

4. The result, which is the mergedArray, is printed to the console.

5. This simple program demonstrates the efficiency of Scala when it comes to performing common tasks such as merging arrays.


Comments