Scala Programming: Find the common elements between two arrays of integers
Scala Programming Array Exercise-15 with Solution
Write a Scala program to find the common elements between two arrays of integers.
Sample Solution:
Scala Code:
object Scala_Array {
def main(args: Array[String]): Unit = {
var nums1 = Array(2,4,5,7,9)
var nums2 = Array(2,3,5,6,9)
//Call the following Java class for some array operation
import java.util.Arrays;
println("Original Array1 : "+Arrays.toString(nums1));
println("Original Array2 : "+Arrays.toString(nums2));
println("Common elements of the said two arrays:")
var i = 0
var j =0;
for (i <- 0 to nums1.length-1)
{
j=0
for (j <- 0 to nums2.length-1)
{
if(nums1(i) == nums2(j))
{
print(s"${nums1(i)}, ")
}
}
}
}
}
Sample Output:
Original Array1 : [2, 4, 5, 7, 9] Original Array2 : [2, 3, 5, 6, 9] Common elements of the said two arrays: 2, 5, 9,
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 value from first, middle and last values of a given array of integers. Array length should be 1 and more and odd.
Next: Write a Scala program to find the common elements between two arrays of strings.
What is the difficulty level of this exercise?
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-15.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics