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.
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.
Program/Source Code:
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.
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer