In this program, we will read elements of the array from the user and count the occurrences of a given item in the one-dimensional array and print the result on the console screen.
The source code to find the occurrence of an item in the array is given below. The given program is compiled and executed successfully.
// Golang program to find the occurrence
// of an item in the array
package main
import "fmt"
func main() {
var arr [5]int
var item int = 0
var count int = 0
fmt.Printf("Enter array elements: \n")
for i := 0; i <= 4; i++ {
fmt.Printf("Elements: arr[%d]: ", i)
fmt.Scanf("%d", &arr[i])
}
fmt.Printf("Enter item: ")
fmt.Scanf("%d", &item)
for i := 0; i <= 4; i++ {
if arr[i] == item {
count = count + 1
}
}
fmt.Printf("Total occurrences of %d are: %d", item, count)
}
Output:
Enter array elements:
Elements: arr[0]: 12
Elements: arr[1]: 34
Elements: arr[2]: 12
Elements: arr[3]: 45
Elements: arr[4]: 12
Enter item: 12
Total occurrences of 12 are: 3
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.
In the main() function, we created an array arr and two more variables item, count.
Program/Source Code:
The source code to find the occurrence of an item in the array is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.
In the main() function, we created an array arr and two more variables item, count.
In the above code, we read elements from the array user and item to be searched.
Here we count the occurrence of items in the array. After that, we printed the count of the item on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer