Q:

Scala program to print the index of the last occurrence of item using lastIndexOf() method

belongs to collection: Scala Array Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to print the index of the last occurrence of an item using the lastIndexOf() 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
// last occurrence of item using lastIndexOf() method

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

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

Output:

Index of last occurrence of value '3' is: 4

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 lastIndexOf() method to get the index of the last occurrence of item 3 in the array. After that, we printed the result on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Scala program to print the common elements of two ... >>
<< Scala program to print the index of the first occu...