find the average of all elements in an array in Go
Code snippet on how to find the average of all elements in an array in Go
package main
import "fmt"
func main() {
arr := []int{1, 2, 3, 4, 5}
sum := 0
for i := 0; i < len(arr); i++ {
sum += arr[i]
}
avg := sum / len(arr)
fmt.Println(avg)
}
This code finds the average of all elements in an array in Go. First, it declares an array ‘arr’ and initializes it with a set of values. Next, the program initializes a variable ‘sum’ to 0. Then a for loop is used to loop through the array and add the elements to the ‘sum’ variable. At the end of the loop, the average of all elements is calculated, the result is divided by the number of elements. Finally, the average is outputted to the console by using the fmt.Println() function.