Q:

Scala program to find the first repeated item in the array

belongs to collection: Scala Array Programs

0

Here, we will create an array of integer elements then we will find the first repeated element in the array. After that, we will print the index of the first repeated element on the console screen.

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 find the first repeated item in the array is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to find the
// first repeated item in the array

import scala.util.control.Breaks._

object Sample {
  def main(args: Array[String]) {
    var IntArray = Array(10, 20, 20, 30, 10, 60)
    var i: Int = 0
    var j: Int = 0

    var item: Int = 0
    var index: Int = 0

    index = -1

    //check first repeated element
    breakable {
      while (i < 6) {
        j = i + 1;
        while (j < 6) {
          if (IntArray(i) == IntArray(j)) {
            item = IntArray(j);
            index = j;
            break;
          }
          j = j + 1;
        }
        i = i + 1
      }
    }

    if (index != -1)
      printf("Item %d repeated at %d index\n", item, index)
    else
      println("There is no repeated element")

  }
}

Output:

Item 10 repeated at 4 index

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 IntArray with 6 elements. Then we found the first repeated item in the array IntArray. After that, we printed the index of the first repeated item 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 multiply two matrices... >>
<< Scala program to find the total occurrences of a g...