w3resource

Scala Programming: Check two numbers, 4 or 7 present in a given array of integers


Write a Scala program to check two numbers, 4 or 7 present in a given array of integers.

Sample Solution:

Scala Code:

object Scala_Array {   
   def test(arr: Array[Int]): Boolean = {
    arr.exists(x => x == 4 || x == 7)
  }   
   def main(args: Array[String]): Unit = {     
    var nums1 = Array(2,4,5,7,9) 
    println("Orginal array:")
    for ( x <- nums1) {
       print(s"${x}, ")        
     }           
    println("\nIf 4 or 7 present in the said array? "+test(nums1))  
    
    var nums2 = Array(2,5,5,6,9) 
    println("Orginal array:")
    for ( x <- nums2) {
       print(s"${x}, ")        
     }          
    println("\nIf 4 or 7 present in the said array? "+test(nums2)) 
    var nums3 = Array(2,5,7,6,9) 
    println("Orginal array:")
    for ( x <- nums3) {
       print(s"${x}, ")        
     }           
    println("\nIf 4 or 7 present in the said array? "+test(nums3))     
  }
}

Sample Output:

Console (F3)
Orginal array:
2, 4, 5, 7, 9, 
If 4 or 7 present in the said array? true
Orginal array:
2, 5, 5, 6, 9, 
If 4 or 7 present in the said array? false
Orginal array:
2, 5, 7, 6, 9, 
If 4 or 7 present in the said array? true

Go to:


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

Scala Code Editor :

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

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.