GO Program to calculate array average

How to calculate array average

Here we are explaining how to calculate array average in the Go program. We can use the built-in function fmt.println() to print anything and fmt.scanln() for reading the values. This function is defined under the fmt package and it helps to write standard output. In order to use these functions, we need to import the “fmt” package.


How to calculate array average using GO Program

We are using fmt.println() function for printing the string to the output screen. Here we are showing how to calculate array average in the Go language. Here variable Arr holds the array elements. Other variables sum, Avg used as the sum of the array and average of the array elements. Use for loop to find the sum of elements by iterating through the loop as sum += Arr[i]. Calculate the average as Avg := sum / 5. Given below are the steps which are used in the Go program. 


STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the variable sum,Avg

STEP 4: assign array Arr[] with elements and sum as 0

STEP 5: Calculate the sum of array elements in a for loop as  sum += Arr[i]

STEP 6: Finally find the average as Avg := sum / 5

STEP 7:Print the sum and Avg using fmt.Println()


GO Source Code

                                          package main
import "fmt"

func main() {
    Arr := [5]int{10, 20, 30, 40, 50}
    sum := 0
    for i := 0; i < 5; i++ {
        sum += Arr[i]

    Avg := sum / 5
    fmt.Println("The average of array items = ", Avg)
    fmt.Println("The sum of array items     = ", sum)


[10 20 30 40 50]
The average of array items =  30
The sum of array items     =  150