Scala program to find the first repeated item in the array

Here, we are going to learn how to find the first repeated item in the array in Scala programming language?
Submitted by Nidhi, on May 26, 2021 [Last updated : March 10, 2023]

Scala – Find the First Repeated Item in an Array

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.

Scala code to find the first repeated item in the array

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.

Scala Array Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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