To count the number of occurrences of a specified element in an array in Go, you can use loops to iterate through the array and count each occurrence.
In this example,
numbers
with values 10, 20, 30, 40, 30, 50.count
to 0 to store the count of occurrences.count
each time element 30 is found.count
will contain the total count of occurrences of element 30.package main
import "fmt"
func main() {
numbers := []int{10, 20, 30, 40, 30, 50}
count := 0
for _, num := range numbers {
if num == 30 {
count++
}
}
fmt.Printf("Number of occurrences of element 30: %d", count)
}
Number of occurrences of element 30: 2
In this example,
fruits
with values 'apple', 'banana', 'cherry', 'banana'.count
to 0 to store the count of occurrences.count
each time element 'banana' is found.count
will contain the total count of occurrences of element 'banana'.package main
import "fmt"
func main() {
fruits := []string{"apple", "banana", "cherry", "banana"}
count := 0
for _, fruit := range fruits {
if fruit == "banana" {
count++
}
}
fmt.Printf("Number of occurrences of element 'banana': %d", count)
}
Number of occurrences of element 'banana': 2
In this tutorial, we learned How to count the Number of Occurrences of Specified Element in the Array in Go language with well detailed examples.