Scala program to print the index of the first occurrence of item using indexOf() method

Here, we are going to learn how to print the index of the first occurrence of item using indexOf() method in Scala programming language?
Submitted by Nidhi, on May 20, 2021 [Last updated : March 10, 2023]

Scala – Finding the Index of the First Occurrence of an Item

Here, we will create an array of integer elements. Then we will use the indexOf() method to get the index of the first occurrence of a given item in the array.

Scala code to print the index of the first occurrence of item using indexOf() method

The source code to print the index of the first occurrence of an item using the indexOf() method is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to print the index of the
// first occurrence of item using indexOf() method

object Sample {
  def main(args: Array[String]) {
    var arr = Array(1, 2, 3, 2, 3);
    var index: Int = 0;

    index = arr.indexOf(3);
    printf("Index of first occurrence of value '3' is: %d\n", index);
  }
}

Output

Index of first occurrence of value '3' is: 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 an array of integers. Then we used the indexOf() method to get the index of the first occurrence of item 3 in the array. After that, we printed the result on the console screen.

Scala Array Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.