w3resource

Scala Programming: Check if a given number is present in fast or last position of a given array of length 1 or more

Scala Programming Array Exercise-2 with Solution

Write a Scala program to check if a given number is present in fast or last position of a given array of length 1 or more.

Sample Solution:

Scala Code:

object Scala_Array {
   def test(x:Int, nums: Array[Int]) : Boolean = {
    if (nums.length < 1) false 
     else nums.head == x || nums.last == x
    }     
   def main(args: Array[String]): Unit = { 
     println("Check if a given number is present in fast or last position in an array!")
     var nums1 = Array(1,2,3,4,5,6)
     var n1 = 5;
     println(s"Given number: ${n1}")
     println("Original Array elements:")
     // Print all the array elements
      for ( x <- nums1 ) {
         print(s"${x}, ")        
       }
      println("\nResult: "+test(n1, nums1))
     var nums2 = Array(1,2,3,4,5,1)
     var n2= 1;
     println(s"Given number: ${n2}")
     println("Original Array elements:")
     // Print all the array elements
      for ( x <- nums2 ) {
         print(s"${x}, ")        
       }
      println("\nResult: "+test(n2, nums2))
   }
}

Sample Output:

Check if a given number is present in fast or last position in an array!
Given number: 5
Original Array elements:
1, 2, 3, 4, 5, 6, 
Result: false
Given number: 1
Original Array elements:
1, 2, 3, 4, 5, 1, 
Result: true

Scala Code Editor :

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

Previous: Write a Scala program to sum values of an given array.
Next: Write a Scala program to calculate the average value of an array of element.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/scala-exercises/array/scala-array-exercise-2.php