Scala program to find the total occurrences of a given item in the array

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

Scala – Find the Occurrences of an Item in an Array

Here, we will create an array of integer elements then we will an item from the array. After that, we will find the total occurrences of the item in the array and print the result on the console screen.

Scala code to find the total occurrences of a given item in the array

The source code to find the total occurrences of a given 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 total occurrences
// of a given item in the array

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

    var count: Int = 0
    var item: Int = 0

    print("Enter ITEM: ");
    item = scala.io.StdIn.readInt();

    //count the occurances of item.
    while (i < 6) {
      if (item == IntArray(i))
        count = count + 1;
      i = i + 1;
    }

    printf("Total occurrences of item(%d) are: %s\n", item, count);
  }
}

Output

Enter ITEM: 10
Total occurrences of item(10) are: 3

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 and an integer variable item. Array IntArray contains 6 items. Then we read the value of the item variable from the user. After that, we found the occurrences of a given item and print the count on the console screen.

Scala Array Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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