w3resource

Scala Programming: Find the index of an element in a given Array

Scala Programming Array Exercise-5 with Solution

Write a Scala program to find the index of an element in a given Array.

Sample Solution:

Scala Code:

object Scala_Array
{
  def main(args: Array[String]): Unit = 
 {
   val colors = Array("Red","Blue","Black","Green","White")
   println("Original Array elements:")
   // Print all the array elements
      for ( x <- colors ) {
         print(s"${x}, ")        
       }
   println("\n")
   println("Index of 'Red':", colors.indexOf("Red"))
   println("Index of 'Blue':", colors.indexOf("Blue"))
   println("Index of 'Black':", colors.indexOf("Black"))
   println("Index of 'Green':", colors.indexOf("Green"))
   println("Index of 'White':", colors.indexOf("White"))   
  }
}

Sample Output:

Original Array elements:
Red, Blue, Black, Green, White, 
(Index of 'Red':,0)
(Index of 'Blue':,1)
(Index of 'Black':,2)
(Index of 'Green':,3)
(Index of 'White':,4)

Scala Code Editor :

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

Previous: Write a Scala program to check if the value of the fast or last element of a given array ( length 1 or more) are same or not.
Next: Write a Scala program to check whether the value of the fast or last element of two given array ( length 1 or more) of integers are same or not.

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