Q:

Scala program to print the common elements of two arrays

belongs to collection: Scala Array Programs

0

Here, we will create two arrays of integer elements. Then we will use intersect() method to get the common elements of both arrays.  The intersect() method return an array that contains common elements.

All Answers

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

Program/Source Code:

The source code to print common elements of two arrays is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to print common elements of two arrays

object Sample {
  def main(args: Array[String]) {
    var arr1 = Array(1, 2, 3, 4, 5);
    var arr2 = Array(6, 7, 1, 2, 8);
    var arr3 = new Array[Int](5);

    var i: Int = 0;

    arr3 = arr1.intersect(arr2);

    println("Common elements of arrays:");
    while (i < arr3.length) {
      printf("%d ", arr3(i));
      i = i + 1;
    }
    println();
  }
}

Output:

Common elements of arrays:
1 2

Explanation:

In the above program, we used an object-oriented approach to create the program. We created an object Sample, and we defined main() function. The main() function is the entry point for the program.

In the main() function, we created two array arr1arr2. Then we used intersect() method to get the common elements of arr1 and arr2. After that, we printed the common elements on the console screen.

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

total answers (1)

Scala Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Scala program to print the distinct elements of th... >>
<< Scala program to print the index of the last occur...