Write a Go Program to calculate the average of array items. The for loop in this Golang example iterates the array items from zero to five. Within the loop (for i := 0; i < 5; i++), we are calculating the sum of array items. Next, we divide the array sum by array size or length, i.e., 5, to get the average.
package main import "fmt" func main() { arrTofindAvg := [5]int{10, 20, 30, 40, 50} fmt.Println(arrTofindAvg) arraySum := 0 for i := 0; i < 5; i++ { arraySum += arrTofindAvg[i] } arrayAvg := arraySum / 5 fmt.Println("The Average of Array Items = ", arrayAvg) fmt.Println("The sum of Array Items = ", arraySum) }
[10 20 30 40 50]
The Average of Array Items = 30
The sum of Array Items = 150
Go Program to Calculate the Average of Array Items using for loop range.
package main import "fmt" func main() { arrTofindAvg := [7]int{15, 25, 35, 45, 55, 65, 75} fmt.Println(arrTofindAvg) arraySum := 0 for _, arr := range arrTofindAvg { arraySum += arr } arrayAvg := arraySum / 7 fmt.Println("The Average of Array Items = ", arrayAvg) fmt.Println("The sum of Array Items = ", arraySum) }
[15 25 35 45 55 65 75]
The Average of Array Items = 45
The sum of Array Items = 315
This Golang program allowed entering the array items and calculated the average of those array elements.
package main import "fmt" func main() { var arrTofindAvg [5]int fmt.Print("Enter the Array Items = ") for i := 0; i < 5; i++ { fmt.Scan(&arrTofindAvg[i]) } fmt.Println(arrTofindAvg) arraySum := 0 for _, arr := range arrTofindAvg { arraySum += arr } arrayAvg := arraySum / 5 fmt.Println("The Average of Array Items = ", arrayAvg) fmt.Println("The sum of Array Items = ", arraySum) }